下面的代码是我用来测试这个特性的。g++编译成功,但运行时出了问题。
#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;
}
输出如下:
6822576
[Done] exited with code=0 in 0.633 seconds
生命周期延长规则仅适用于临时对象;而AA
是一个局部对象,当ff
返回时将被销毁。即使在return
语句中绑定了ff
的返回值,它的生存期也不会延长。ff()
总是返回一个悬空引用,ff()[0]
指向UB。