[英]rvalue reference—"An rvalue may be used to initialize an rvalue reference to extend its lifetime until the scope of the reference ends."
下面的代码是我用来测试该功能的代码。 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;
}
output如下:
6822576
[Done] exited with code=0 in 0.633 seconds
终身延长规则只适用于临时工; 而AA
是本地的 object 并且会在ff
返回时被销毁。 即使在return
语句中绑定到ff
的返回值,它的生命周期也不会延长。 ff()
总是返回悬空引用,而ff()[0]
导致 UB。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.