做右值引用允许悬挂引用? [英] Do rvalue references allow dangling references?
问题描述
请考虑以下内容。
#include< string&
using std :: string;
string middle_name(){
returnJaan;
}
int main()
{
string&& danger = middle_name(); //?!
return 0;
}
这不计算任何东西,但它编译没有错误,我发现混淆: danger
是一个悬挂的引用,不是吗?
如果您的意思是可以创建悬挂,您可以创建悬挂引用? 右值引用,那么答案是肯定的。
string middle_name(){
returnJaan;
}
int main()
{
string&& nodanger = middle_name(); // 好。
//临时的生命周期扩展为
//到引用的生命周期。
return 0;
}
此处适用相同的规则,使此示例< a>(Herb Sutter的文章)安全。如果您使用 右值初始化引用,则tempoary对象的生命周期将延长到引用的生命周期。你仍然可以产生悬挂引用。例如,这不再安全:
int main()
{
string&& danger = std :: move(middle_name()); // dangling reference!
return 0;
}
因为
std :: move
返回string&&&
( pure 右值)延长临时生命周期的规则不适用。这里,std :: move
返回所谓的 xvalue 。 xvalue 只是一个未命名的右值引用。因此,它可以引用任何东西,基本上不可能猜到返回的引用指向什么,而不查看函数的实现。Consider the below.
#include <string> using std::string; string middle_name () { return "Jaan"; } int main () { string&& danger = middle_name(); // ?! return 0; }
This doesn't compute anything, but it compiles without error and demonstrates something that I find confusing:
danger
is a dangling reference, isn't it?解决方案Do rvalue references allow dangling references?
If you meant "Is it possible to create dangling rvalue references" then the answer is yes. Your example, however,
string middle_name () { return "Jaan"; } int main() { string&& nodanger = middle_name(); // OK. // The life-time of the temporary is extended // to the life-time of the reference. return 0; }
is perfectly fine. The same rule applies here that makes this example (article by Herb Sutter) safe as well. If you initialize a reference with a pure rvalue, the life-time of the tempoary object gets extended to the life-time of the reference. You can still produce dangling references, though. For example, this is not safe anymore:
int main() { string&& danger = std::move(middle_name()); // dangling reference ! return 0; }
Because
std::move
returns astring&&
(which is not a pure rvalue) the rule that extends the temporary's life-time doesn't apply. Here,std::move
returns a so-called xvalue. An xvalue is just an unnamed rvalue reference. As such it could refer to anything and it is basically impossible to guess what a returned reference refers to without looking at the function's implementation.这篇关于做右值引用允许悬挂引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!