forward_list,设置,列表等如何调用标准::分配器

How do forward_list,set,list etc call std::allocator?

本文关键字:调用 标准 分配器 list 设置 列表 forward 何调用      更新时间:2023-10-16

我注意到分配器只能分配 T 类型的对象并保留大小为 n * sizeof(T) 的内存块。但是,std::list<T>类型中的链表节点不一定是 T 类型的对象,也不一定与T对象的大小相同。在这种情况下,std::list如何使用std::allocator来分配内存?

这就是重新绑定类型存在的原因。它允许您创建一个类似的分配器,而不是分配其他内容(例如node<T>)。

基本上是这样的:

std::allocator<int> int_alloc;
std::allocator<int>::rebind<node<int>> node_alloc;
//Perhaps more useful:
decltype(int_alloc)::rebind<node<int>> node_alloc;

当然,在真实情况下,这一切都会被模板化,但希望这能表明这个想法。

有关更多信息,请阅读此处的注释和示例。