Possible Duplicate:
Does a const reference prolong the life of a temporary?
我的编译器不会提示将临时分配给 const 引用:
string foo() {
return string("123");
};
int main() {
const string& val = foo();
printf("%s\n", val.c_str());
return 0;
}
为什么?我认为从 foo
返回的字符串是临时的,并且 val 可以指向生命周期已结束的对象。 C++ 标准是否允许这样做并延长返回对象的生命周期?
最佳答案
这是一个 C++ 功能。该代码是有效的,并且完全按照它看起来要做的那样做。
通常,临时对象只会持续到它出现的完整表达式的末尾。但是,C++ 特意指定将临时对象绑定(bind)到堆栈上的 const 引用会将临时对象的生命周期延长到引用本身的生命周期,从而避免常见的悬空引用错误。在上面的示例中,由 foo()
返回的临时值一直存在到右花括号为止。
PS:这仅适用于基于堆栈的引用。它不适用于作为对象成员的引用。
全文:GotW #88: A Candidate For the “Most Important const” by Herb Sutter .
关于c++ - 返回临时对象并绑定(bind)到 const 引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11560339/