简体   繁体   中英

rvalue reference—"An rvalue may be used to initialize an rvalue reference to extend its lifetime until the scope of the reference ends."

The code below is what i used to test the feature. G++ compiled it successfully but something went wrong when running it.

#include <iostream>
#include <vector>

using namespace std;

vector<int> &&ff()
{
    vector<int> AA({1, 2, 4, 
5, 7, 8});
    return std::move(AA);
}

int main(void)
{
    cout << ff()[0] << endl;

    return 0;
}

The output is as follows:

6822576

[Done] exited with code=0 in 0.633 seconds

Lifetime extension rule only works for temporaries; while AA is a local object and would be destroyed when ff returns. Its lifetime won't be extended even it's bound to the return value of ff in the return statement. ff() always returns a dangling reference and ff()[0] leads to UB.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM