Mer*_*rni 5 c++ templates memory-management
每个 stl 容器都采用一个分配器作为参数:
template < class T, class Allocator = allocator<T> > class vector;
Run Code Online (Sandbox Code Playgroud)
如果您编写自己的类,则可以使用自己的分配器。但是是否可以在不使用模板的情况下编写自己的分配器?
例如,如果不允许使用模板,则编写此函数并不容易
pointer allocate(size_type n, const_pointer = 0) {
void* p = std::malloc(n * sizeof(T));
if (!p)
throw std::bad_alloc();
return static_cast<pointer>(p);
}
Run Code Online (Sandbox Code Playgroud)
因为你怎么知道 T 的大小呢?
好吧,如果您编写的不是模板类,那么它必须仅适用于单一类型。只需替换T为您想要分配器的任何类型即可。
看起来像是一个毫无意义的练习,因为实际上您确实有可用的模板。