为什么std::allocator::construct和std::allocator::destroy要以元素类型为模板参数?

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*pointer?这样做的理由是什么?看起来,allocator<T>应该只知道如何构造或销毁类型T的对象。

1个回答

16
由于许多容器从不分配T,因此需要allocator具有rebind<U> typedef。以链表为例,它们分配节点,每个节点的成员都含有一个T。所以,allocator需要能够分配一些未知类型(通过rebind<U>)。然而,这需要进行复制操作:需要创建一个新的rebind<U>::other类型的分配器。尽可能避免这种情况更好。因此,在构建和销毁过程中,需要allocator对任何类型执行适当的操作,例如链表内部节点类型。这也使得链表的内部节点类型可以将Allocator::construct/destruct作为友元函数。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接