STD ::列表对其分配器参数有什么作用

What does the std::list do with its allocator argument?

本文关键字:什么 作用 参数 列表 STD 分配器      更新时间:2023-10-16

std::list是通过分配类型进行参数化的,它大概可以重新启动以分配列表节点而不是 T s。那么,它与传递给构造函数的分配器类型的对象有什么关系?

template <class T, class Alloc = std::allocator<T>>
class list
{
    class node { ... T element; ... };
    using real_alloc =
        typename std::allocator_traits<Alloc>::template rebind_alloc<node>;
    real_alloc m_allocator;
public:
    list(const Alloc&);
};

在上述代码中,我们需要将m_allocator初始化为节点分配器,但是将构造函数赋予T分配器。我们只是将T分配器放在地板上,还是以某种方式使用?

,因为C++11分配器可以说明。您需要使用用户提供的内部分配器来构建内部分配器。明确需要从typename std::allocator_traits<Alloc>::template rebind_alloc<U>构造分配器。

列表构造函数的实现应该看起来像:

template<class T, class Alloc>
class list
{
      struct node_type {/*etc*/}; //internal
      using allocator_type_internal = typename std::allocator_traits<Alloc>::template rebind_alloc<node_type>;
      // etc.
      allocator_type_internal m_allocator; //Note we use allocator_type, not Alloc.
};
list::list(const Alloc& alloc ) : 
     m_allocator(alloc)
{ /* initialize sentinel node, etc. */ }

虽然一个良好的实现将对分配器使用空基本优化。

T分配器仍用于construct()destroy()内部节点的T部分。在构建过程中添加自定义参数可能需要使用这些操作,例如,可选地将合适的分配器参数转发到构造的对象。