Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 807
aerain Avatar asked Dec 04 '22 02:12

aerain


1 Answers

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.

like image 137
MvG Avatar answered Dec 19 '22 07:12

MvG