What does std::vector look like in memory?

前端 未结 6 694
耶瑟儿~
耶瑟儿~ 2021-02-01 13:10

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

6条回答
  •  梦谈多话
    2021-02-01 13:45

    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 the numbers 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.

提交回复
热议问题