c++ - 临时对象被销毁后为什么不崩溃

标签 c++

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/

相关文章:

c++ - 有或没有 reinterpret_cast

c++ - native C++ 中的并行同步迭代任务

c++ - static_cast 和 reinterpret_cast 的转换运算符 int() 失败

使用框架绘制 Sprite 时C++ Sfml白色方 block

c++ - Qt jom.exe错误2

c++ - whitecards(小写)跳过 PlayerVector 中的其他玩家,但第一个 - 为什么?

c++ - 如何在 Arduino 的函数中定义全局数组的长度?

c++ - 将纯虚拟更改为虚拟并保持二进制兼容

c++ - 接收字符串并使用它来调用 C++ 方法

c++ - 'int [0]' c++ 的初始值设定项太多