class C
{
public:
int True(int i) const
{
return i+2;
}
};
const C& F(const C& c)
{
return c;
}
int main()
{
const C& c = F(C()); // Line 1
cout << boolalpha << c.True(1) << endl; // Line 2
}
问题> 为什么上面的代码可以打印出正确的值?
我假设变量 c
在到达第 2 行时将引用一个无效的临时 C
对象。
//更新
我想更新此 OP 以说明我关注此问题的原因。
这是来自 C++ 模板的代码片段:完整指南
// maximum of two values of any type
template <typename T>
inline T const& max (T const& a, T const& b)
{
return a < b ? b : a;
}
如您所见,函数返回对传入参数的引用。 我只是想知道为什么不使用以下版本:
// maximum of two values of any type
template <typename T>
inline T max (T const& a, T const& b)
{
return a < b ? b : a;
}
最佳答案
C++11 标准的第 12.2/4 段规定,在某些情况下临时对象的生命周期确实可以延长到生成它们的完整表达式的末尾之外:
There are two contexts in which temporaries are destroyed at a different point than the end of the full expression. [...]
第一个上下文不相关。但是,根据第 12.2/5 段:
The second context is when a reference is bound to a temporary. The temporary to which the reference is bound or the temporary that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference except:
— A temporary bound to a reference member in a constructor’s ctor-initializer (12.6.2) persists until the constructor exits.
— A temporary bound to a reference parameter in a function call (5.2.2) persists until the completion of the full-expression containing the call.
— The lifetime of a temporary bound to the returned value in a function return statement (6.6.3) is not extended; the temporary is destroyed at the end of the full-expression in the return statement.
— A temporary bound to a reference in a new-initializer (5.3.4) persists until the completion of the full-expression containing the new-initializer.
在这里,用C()
构造的临时变量绑定(bind)到函数F
的参数c
。因此,临时对象在包含对函数 F()
的调用的完整表达式的末尾被销毁,并且返回的引用是悬空。
在其上调用函数 True()
会导致未定义的行为。
关于c++ - 临时对象被销毁后为什么不崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14989183/