为什么value_type将std :: list分配器参数化为默认值?

问题描述 投票:1回答:1
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;
}
c++ memory-management std
1个回答
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>>,则可以为rebind提供成员模板Alloc,然后提供the allocator Alloc::rebind<Node<T>>::other will be used

© www.soinside.com 2019 - 2024. All rights reserved.