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;
}
请参见cppreference,std::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。