返回临时对象并绑定到const引用
我的编译器没有抱怨将临时赋值给const引用:
My compiler doesn't complain about assigning temporary to const reference:
string foo() {
return string("123");
};
int main() {
const string& val = foo();
printf("%s\n", val.c_str());
return 0;
}
为什么?我认为从 foo
返回的字符串是临时的,val可以指向生命周期结束的对象。 C ++标准允许这样做并延长返回对象的生命周期?
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?
这是一个C ++特性。
This is a C++ feature. The code is valid and does exactly what it appears to do.
通常,临时对象只能持续到它出现的完整表达式的结尾。然而,C ++有意地指定将临时对象绑定到对堆栈的引用将延长临时的生存期到引用本身的生命周期,从而避免了否则将是常见的悬挂 - 引用错误。在上面的示例中, foo()
返回的临时变量直到关闭大括号。
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.
P.S:这仅适用于基于堆栈的引用。它不适用于作为对象成员的引用。
P.S: This only applies to stack-based references. It doesn’t work for references that are members of objects.