【问题标题】:Why are std::allocator::construct and std::allocator::destroy templated on element type?为什么 std::allocator::construct 和 std::allocator::destroy 以元素类型为模板?
【发布时间】:2012-05-11 00:49:32
【问题描述】:

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&lt;T&gt; 应该只知道如何构造或销毁T 类型的对象。

【问题讨论】:

    标签: c++ c++11 allocation allocator


    【解决方案1】:

    出于同样的原因,allocators 必须具有 rebind&lt;U&gt; 类型定义:因为许多容器从不分配 Ts。

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

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

    【讨论】:

      猜你喜欢
      • 2014-01-31
      • 1970-01-01
      • 2017-06-22
      • 1970-01-01
      • 2021-02-05
      • 1970-01-01
      • 1970-01-01
      • 2019-08-22
      • 2019-02-25
      相关资源
      最近更新 更多