Can I assume that for any type T, the type std::list<T> will have a same, constant size? Just to make it clear, I mean the size of the ‘main’ type itself only, not of the memory allocated by it.
It seems logical to me to assume that the size of T itself should only affect the size of list nodes allocated using the allocator.
However, there are two things that might cause the variancy of sizeof(std::list<T>) I can think of:
- A standard C++ library trying to ‘optimize’ the
std::listtype by putting some ofTinstances into thestd::list<T>itself. That seems like a bad idea to me, and it probably breaks the ‘constant time’ requirements put by the standard; - A standard C++ having library specializations of
std::list<T>for some types, with the specializations having different sizes.
I can’t think of any uses for (1) or (2) but I may be wrong.
What I’m thinking of achieving is using a fixed-size slice allocator for a template class usingstd::list<T> inside.
As a note: this is about variance for different types of T, and not for different allocators. I will have an explicit control of all instantiations, and they all will use the std::allocator.
Yes, it can.
The standard does not precise any guarantee on the size of a
list<T>object as far as I am aware. Still, there are other guarantees.Let us debunk some things:
It does not break the ‘constant time’ requirement in any way as long as this number is bounded since O(5) is O(1). However, during a
spliceoperations, the nodes should move from one list to another without moving in memory. Thus local storage is prohibited.Since we already excluded the possibility of local storage, it is hard to imagine any other variations of the base
std::list<T>type by itself.And let us worry about what matters:
The memory allocated by a
std::list<T>is provided by its second template argument: the allocator. Most allocators (includingstd::allocator<T>which is the default) use a simple pointer type:T*… however an allocator should feel free to change this type.Therefore, by changing the
allocatorparameter (and more precisely, its pointer type), one will naturally change the size of thestd::listcontainer in all the implementations I have seen of it.Note that the allocator itself could be specialized for some types, however with the rebind magic it’s a bit more difficult to achieve.