user3064869
user3064869

Reputation: 530

Why are stack-allocated elements stored in C++ STL vector still alive even if out of scope?

I have the following code:

#include <vector>
#include <iostream>

using namespace std;

int main(int argc, char* argv[]) {

    vector<int > vi;

    for(int i=0; i<10; i++) {
        int j=i*i;
        vi.push_back(j);
    }

    for(int i=0; i<(int)vi.size(); i++)
        cout<<vi[i]<<" ";
    cout<<endl;

    return 1;

}

Executing this code returns "0 1 4 9 16 25 36 49 64 81", but this is not intuitive for me.

As far as I know, when variables get allocated on the stack, the variables are de-allocated when it gets out of scope. I also know that C++ STL vectors store pointers to variables. Why is it that the vector still holds valid integers despite the integers got allocated on stack and gets out of scope? Shouldn't the pointers that the vector hold get nulled because integers got de-allocated?

Upvotes: 0

Views: 209

Answers (1)

quantdev
quantdev

Reputation: 23803

I also know that C++ STL vectors store pointers to variables.

No, standard containers store values. The std::vector holds a pointer to a dynamic allocated internal array of values (in your case, int).

Your ints are copied in the vector, which is why it works (without value semantics, the containers would be unusable in many cases)

Upvotes: 6

Related Questions