How does std::list allocate nodes vs. elements

折月煮酒 提交于 2019-12-10 03:21:26

问题


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 type Node<T>, using the allocator A::rebind<Node<T>>::other

since C++11

std::list<T, A> allocates nodes of some internal type Node<T>, using the allocator std::allocator_traits<A>::rebind_alloc<Node<T>>, which is implemented in terms of A::rebind<Node<T>>::other if A is an std::allocator



来源:https://stackoverflow.com/questions/24974935/how-does-stdlist-allocate-nodes-vs-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!