我遇到了以下代码片段
std::string&& test()
{
std::string m="Hello";
return (std::move(m));
}
int main()
{
std::string&& m = test();
}
我知道上面的代码不正确且不安全,但我不确定为什么。
到目前为止,这是我对代码的理解。在函数 test
在堆栈上创建了一个名为
m
的本地std::string
变量。然后返回此字符串,但它的内容被 move 到临时文件中,而不是制作拷贝。此时函数
test
结束调用变量m
的析构函数(其内容已移至 temp)临时对象现在绑定(bind)到右值引用
m
。据我了解,临时对象将保持事件状态,直到其绑定(bind)对象处于事件状态并在范围内。
有人可以告诉我我可能哪里出错了吗?为什么上面的代码不安全?
最佳答案
右值引用仍然是引用,您的代码不正确的原因与下面显示的函数相同
std::string& test()
{
std::string m="Hello";
return m;
}
在这两种情况下,函数都会返回对局部变量的引用。 std::move
除了将 m
转换为 string&&
之外不做任何事情,因此在 main
中没有临时创建 m
然后绑定(bind)到。当test
退出时,局部变量被销毁,m
是悬空引用。
要修复您的代码,请将返回类型从 string&&
更改为 string
。
std::string test()
{
std::string m="Hello";
return m; // std::move is redundant, string will be moved automatically
}
int main()
{
std::string&& m = test();
}
现在main
中的m
可以绑定(bind)到test
的返回值,lifetime of that is extended匹配m
。
关于c++ - 返回一个右值——这段代码有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31924678/