I read that std::vector
should be contiguous. My understanding is, that its elements should be stored together, not spread out across the memory. I have simply acce
It roughly looks like this (excuse my MS Paint masterpiece):
The std::vector
instance you have on the stack is a small object containing a pointer to a heap-allocated buffer, plus some extra variables to keep track of the size and and capacity of the vector.
So it seems as though when I
push_back()
to thenumbers
vector, its older elements change their location.
The heap-allocated buffer has a fixed capacity. When you reach the end of the buffer, a new buffer will be allocated somewhere else on the heap and all the previous elements will be moved into the new one. Their addresses will therefore change.
Does it maybe store them together, but moves them all together, when more space is needed?
Roughly, yes. Iterator and address stability of elements is guaranteed with std::vector
only if no reallocation takes place.
I am aware, that
std::vector
is a contiguous container only since C++17
The memory layout of std::vector
hasn't changed since its first appearance in the Standard. ContiguousContainer is just a "concept" that was added to differentiate contiguous containers from others at compile-time.