繁体   English   中英

右值引用——“右值可用于初始化右值引用以延长其生命周期,直到引用的 scope 结束。”

[英]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.

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