std::vector internals

前端 未结 3 1068
忘掉有多难
忘掉有多难 2021-01-21 05:50

How is std::vector implemented, using what data structure? When I write

void f(int n) {
  std::vector v(n);
  ...
}

Is

相关标签:
3条回答
  • 2021-01-21 06:15

    The vector object will be allocated on the stack and will internally contain a pointer to beginning of the elements on the heap.

    Elements on the heap give the vector class an ability to grow and shrink on demand.

    While having the vector on the stack gives the object the benefit of being destructed when going out of scope.

    In regards to your [] question, the vector class overloads the [] operator. I would say internally it's basically doing something like this when you do array[1]:

    return *(_Myfirst+ (n * elementSize))
    

    Where the vector keeps track of the start of it's internal heap with _Myfirst.

    When your vector starts to fill up, it will allocate more memory for you. A common practice is to double the amount of memory needed each time.

    Note that vector inherits from _Vector_val, which contains the following members:

    pointer _Myfirst;   // pointer to beginning of array
    pointer _Mylast;    // pointer to current end of sequence
    pointer _Myend; // pointer to end of array
    _Alty _Alval;   // allocator object for values
    
    0 讨论(0)
  • 2021-01-21 06:34

    Your v is allocated in automatic memory. (commonly known as the stack, yes)

    The implementation details are not specified, but most commonly it's implemented using a dynamic array which is resized if you attempt to add more elements than the previous allocation can hold.

    The standard only specifies the interface (which methods it should have) and execution time boundaries.

    Since vector is a template, the implementation is visible, so locate your <vector> file and start inspecting.

    0 讨论(0)
  • 2021-01-21 06:39
    void f(int n) {
      std::vector<int> v(n);
      ...
    }
    

    The vector above has automatic storage duration and is allocated on the stack. However, the data array that the vector manages is allocated on the heap.

    The internals of the vector are implementation specific, but a typical implementation will contain 3 pointers; one each to keep track of start of array, size of vector and capacity of vector.

    0 讨论(0)
提交回复
热议问题