aerain
aerain

Reputation: 1179

How does a stack-allocated vector expand in c++?

If I declare a vector like so:

int main() {
    vector<string> names;
    int something_else_on_the_stack = 0;
    names.add("John");
    names.add("Annie");
}

How are you actually able to "add" elements to the names vector? If names is stack-allocated, shouldn't "something_else_on_the_stack" be right after it on the stack? Then how can you add names to the already allocated vector?

Upvotes: 4

Views: 841

Answers (3)

Praetorian
Praetorian

Reputation: 109169

The size that a vector<string> occupies on the stack is fixed, and will typically be equal to the size of 3 pointers (this is implementation specific). The pointers point to beginning of storage, vector capacity and vector size. These pointers point to free store memory (or heap, if you want to call it that) that the vector allocates as needed to hold objects you add to the vector.

Upvotes: 2

MvG
MvG

Reputation: 60918

Internally, a vector<string> will most likely consist of a string* pointing at the actual data and probably two more size_t members indicating occupied and reserved memory. All the rest will be on the heap. Therefore, sizeof(vector<string>) is fixed, and the allocation on the stack won't change.

Upvotes: 8

Henrik
Henrik

Reputation: 23324

std::vector internaly maintains a pointer to heap allocated space that is resized as necessary. The footprint on the stack doesn't change.

Upvotes: 7

Related Questions