C++ 返回临时对象并绑定到 const 引用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11560339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Returning temporary object and binding to const reference
提问by gruszczy
Possible Duplicate:
Does a const reference prolong the life of a temporary?
可能的重复:
const 引用是否会延长临时引用的寿命?
My compiler doesn't complain about assigning temporary to const reference:
我的编译器不会抱怨将临时分配给 const 引用:
string foo() {
return string("123");
};
int main() {
const string& val = foo();
printf("%s\n", val.c_str());
return 0;
}
Why? I thought that string returned from foo
is temporary and val can point to object which lifetime has finished. Does C++ standard allow this and prolongs the lifetime of returned object?
为什么?我认为从返回的字符串foo
是临时的,而 val 可以指向生命周期已结束的对象。C++ 标准是否允许这样做并延长返回对象的生命周期?
回答by Sergey K.
This is a C++ feature. The code is valid and does exactly what it appears to do.
这是一个 C++ 特性。该代码是有效的,并且完全符合它的功能。
Normally, a temporary object lasts only until the end of the full expression in which it appears. However, C++ deliberately specifies that binding a temporary object to a reference to const on the stack lengthens the lifetime of the temporary to the lifetime of the reference itself, and thus avoids what would otherwise be a common dangling-reference error. In the example above, the temporary returned by foo()
lives until the closing curly brace.
通常,临时对象仅持续到它出现的完整表达式的结尾。但是,C++ 特意指定将临时对象绑定到堆栈上对 const 的引用会将临时对象的生命周期延长到引用本身的生命周期,从而避免常见的悬空引用错误。在上面的例子中,临时返回的foo()
生命直到结束花括号。
P.S:This only applies to stack-based references. It doesn't work for references that are members of objects.
PS:这仅适用于基于堆栈的引用。它不适用于作为对象成员的引用。
Full text: GotW #88: A Candidate For the “Most Important const” by Herb Sutter.