为什么std :: allocator :: construct和std :: allocator :: destroy模板化元素类型?

Jar*_*ock 8 c++ allocation allocator c++11

std::allocatorconstructdestroy成员函数上构造元素的类型参数化:

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);

  ...
};
Run Code Online (Sandbox Code Playgroud)

这是什么理由?为什么他们不采取value_type*pointer?似乎allocator<T>应该只知道如何构造或销毁类型的对象T.

Nic*_*las 16

出于同样的原因,allocators需要具有rebind<U>typedef:因为许多容器从不分配Ts.

获取链接列表.这些分配节点,其中的每一个包含一个T作为成员.所以allocators需要能够分配一些他们不知道的类型(via rebind<U>).但是,这需要复制操作:它需要创建该类型的新分配器rebind<U>::other.

最好在可能的情况下避免这种情况.因此,对于构造和销毁,分配器需要对任何类型执行适当的操作,例如链表的内部节点类型.这也使得链表的内部节点类型可以具有Allocator::construct/destruct友元功能.