c++ Vector, what happens whenever it expands/reallocate on stack?

后端 未结 7 743
情深已故
情深已故 2020-11-29 00:51

I\'m new to C++ and I\'m using the vector class on my project. I found it quite useful because I can have an array that automatically reallocates whenever it is necessary (

7条回答
  •  [愿得一人]
    2020-11-29 01:18

    The way you construct your vector (stack or heap) doesn't matter for this.

    See the documentation for std::vector

    Internally, vectors use a dynamically allocated array to store their elements. This array may need to be reallocated in order to grow in size when new elements are inserted, which implies allocating a new array and moving all elements to it.

    When a vector "grows", the vector object doesn't grow, only the internal dynamic array changes.

    As for its implementation, you can look at GCC's vector implementation.

    To keep it simple, it declares vector as a class with one protected member, of type _Vector_impl.

    As you can see, it is declared as a structure that contains three pointers :

    • One that points at the beginning of the storage (and the beginning of the data)
    • One that points at the end of the data
    • One for the end of the storage

提交回复
热议问题