What does std::vector look like in memory?

前端 未结 6 684
耶瑟儿~
耶瑟儿~ 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:40

    So what does it exactly mean, that std::vector is a contiguous container and why do its elements move? Does it maybe store them together, but moves them all together, when more space is needed?

    That's exactly how it works and why appending elements does indeed invalidate all iterators as well as memory locations when a reallocation takes place¹. This is not only valid since C++17, it has been the case ever since.

    There are a couple of benefits from this approach:

    • It is very cache-friendly and hence efficient.
    • The data() method can be used to pass the underlying raw memory to APIs that work with raw pointers.
    • The cost of allocating new memory upon push_back, reserve or resize boil down to constant time, as the geometric growth amortizes over time (each time push_back is called the capacity is doubled in libc++ and libstdc++, and approx. growths by a factor of 1.5 in MSVC).
    • It allows for the most restricted iterator category, i.e., random access iterators, because classical pointer arithmetic works out well when the data is contiguously stored.
    • Move construction of a vector instance from another one is very cheap.

    These implications can be considered the downside of such a memory layout:

    • All iterators and pointers to elements are invalidate upon modifications of the vector that imply a reallocation. This can lead to subtle bugs when e.g. erasing elements while iterating over the elements of a vector.
    • Operations like push_front (as std::list or std::deque provide) aren't provided (insert(vec.begin(), element) works, but is possibly expensive¹), as well as efficient merging/splicing of multiple vector instances.

    ¹ Thanks to @FrançoisAndrieux for pointing that out.

提交回复
热议问题