问题
How does std::list
allocate the nodes in which it keeps the next
/prev
pointers and the T
element it contains?
I think that standard allocators can only be used to allocate memory for one type (because std::allocator::allocate
allocates memory in increments of sizeof(T)
). So it seems impossible to allocate the list node and the contained object in a single allocation, which means that the nodes have to be allocated with whatever the implementation decides, and the nodes store pointers to the objects instead of the objects themselves, and this implies two levels of indirection to get from a pointer to a list node to the object it contains, which seems inefficient. Is this the case?
回答1:
The allocator has a member template class, rebind, which is responsible for allocating other types. The page for std::allocator
here actually has an example of the exact thing you are asking. I will quote it here:
until C++11
std::list<T, A>
allocates nodes of some internal typeNode<T>
, using the allocatorA::rebind<Node<T>>::other
since C++11
std::list<T, A>
allocates nodes of some internal typeNode<T>
, using the allocatorstd::allocator_traits<A>::rebind_alloc<Node<T>>
, which is implemented in terms ofA::rebind<Node<T>>::other
if A is anstd::allocator
来源:https://stackoverflow.com/questions/24974935/how-does-stdlist-allocate-nodes-vs-elements