std::allocator的construct和destroy成员函数根据要构造的元素的类型进行参数化:
template<class T>
class allocator
{
public:
typedef T value_type;
typedef T* pointer;
template<class U, class... Args>
void construct(U *p, Args&&... args);
template<class U>
void destroy(U *p);
...
};这样做的理由是什么?他们为什么不选择value_type*或pointer呢?看起来allocator<T>应该只知道如何构造或销毁T类型的对象。
发布于 2012-05-11 09:08:01
这与要求allocator具有rebind<U>类型定义f的原因是相同的:因为许多容器从不分配T。
以链表为例。它们分配节点,每个节点都包含一个T作为成员。所以allocator需要能够分配一些他们不知道的类型(通过rebind<U>)。但是,这需要一个复制操作:它需要创建一个类型为rebind<U>::other的新分配器。
最好在可能的情况下避免这种情况。因此,对于构造和销毁,分配器需要对任何类型执行适当的操作,例如链表的内部节点类型。这也使得链表的内部节点类型可以使用Allocator::construct/destruct作为友元函数。
https://stackoverflow.com/questions/10544014
复制相似问题