2020-10-29

How comes the lifetime of a local variable inside a function be extended?

See the code below. v1 is local variable inside a function. Accordingly, after leaving this fucntion, this variable should be killed. Thus, the move constructor should run into problem in the main function. But actually the outcome is the opposite. In the main function, I can see the contents of v1.

#include <iostream>

#include <vector>

using namespace std;

void my_fn(vector<vector<int>> & v) {
    vector<int> v1 = {1, 2, 3};
    v.push_back(move(v1));
    cout << " " << endl;
}

int main(){
    vector<vector<int>>  v;
    my_fn(v);
    for(const auto & e:v)
        for (const auto e1: e)
            cout << e1 << endl;

    return 0;
}


from Recent Questions - Stack Overflow https://ift.tt/31TeGrA
https://ift.tt/eA8V8J

No comments:

Post a Comment