Search code examples
variablesconstructorlocalmove

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;
}

Solution

  • When you move the contents of v1 into v, v1 is not yet destroyed because that happens right before the closing bracket of the function my_fn. As a result, the contents of v1 are pushed into v which is taken by reference. The scope of v1 is not extended but its content is just copied.