Cartesius00
Cartesius00

Reputation: 24404

std::vector internals

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

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

Is the vector v allocated on stack?

Upvotes: 3

Views: 2644

Answers (3)

Aesthete
Aesthete

Reputation: 18848

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

Upvotes: 6

Praetorian
Praetorian

Reputation: 109229

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.

Upvotes: 2

Luchian Grigore
Luchian Grigore

Reputation: 258638

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.

Upvotes: 5

Related Questions