8

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

  ...
};

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

4

1 回答 1

16

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

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

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

于 2012-05-11T01:08:00.707 回答