为什么 std::list 分配器被 value_type 参数化为默认值?
Why is an std::list allocator parameterised by the value_type as a default?
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>
使用 std::allocator_traits<Allocator>::rebind_alloc<Node<T>>
分配其内部节点(比如 class Node<T>
),默认情况下,[=13] =] 如果 Allocator
是 Alloc<T, Args>
。因此,当使用 std::allocator
时,std::list<T>
将使用 std::allocator<Node<T>>
分配其内部节点。
如果您想提供自定义分配器模板 Alloc
并且不希望 std::list<T>
使用 Alloc<Node<T>>
,您可以为 Alloc
,然后 the allocator Alloc::rebind<Node<T>>::other
will be used。
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>
使用 std::allocator_traits<Allocator>::rebind_alloc<Node<T>>
分配其内部节点(比如 class Node<T>
),默认情况下,[=13] =] 如果 Allocator
是 Alloc<T, Args>
。因此,当使用 std::allocator
时,std::list<T>
将使用 std::allocator<Node<T>>
分配其内部节点。
如果您想提供自定义分配器模板 Alloc
并且不希望 std::list<T>
使用 Alloc<Node<T>>
,您可以为 Alloc
,然后 the allocator Alloc::rebind<Node<T>>::other
will be used。