c++ - 为什么默认由value_type参数化std::list分配器?

标签 c++ memory-management std

template <
  class T,
  class Allocator = std::allocator<T>
>
class list;

通过声明一个std::list<int>变量,如下所示,我将确保std::list<int>::allocator_type的类型为std::allocator<int>。假设有一个双向链表实现,则每个内部节点都将大于value_type的大小。这是否意味着一个实现将在每次插入元素时分配两次内存?一次用于元素,一次用于节点?上面显示了std::list的前向声明以供引用。
int main(int argc, char *argv[])
{
  std::list<int> mylist;
  mylist.push_front(9);
  return 0;
}

最佳答案

参见cppreferencestd::list<T>使用Node<T>分配其内部节点(例如std::allocator_traits<Allocator>::rebind_alloc<Node<T>>类),如果Alloc<Node<T>, Args>Allocator,则默认为Alloc<T, Args>。因此,当使用std::allocator时,std::list<T>将使用std::allocator<Node<T>>分配其内部节点。

如果要提供自定义分配器模板Alloc,并且不想std::list<T>使用Alloc<Node<T>>,则可以为rebindthe allocator Alloc will be used提供成员模板Alloc::rebind<Node<T>>::other

关于c++ - 为什么默认由value_type参数化std::list分配器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60495366/

相关文章:

c++ - 将 vector 传递给函数(指针/地址)

c++ - std::priority_queue 复杂类型?

c - fread() 返回零字节读取 : I Don't Understand Why

c++ - 使用虚拟成员从类制作 POD

c++ - C关键字/函数是否未包含在C++的std namespace 中?

c++ - 在 C++ 中创建动态数据类型

objective-c - 为什么它不崩溃?

c++ - 释放内存时出错

c - 将内存公开为只读

c++ - C++如何在二维 vector 初始化中创建不同的 vector ?