c++ - 不是最重要的 const.. 但这是什么?

标签 c++ reference constants object-lifetime

这输出 F~ 但我期待的是 ~F

#include <iostream>

struct Foo {
    int _x;
    operator const int & () const {return _x;}
    ~ Foo () {std :: cout << "~";}
};

void foo (const int &)
{
    std :: cout << "F";
}

int main ()
{
    foo (Foo ());
}

我将其构建为一个反例,以表明最重要的常量是异常(exception)而非规则。一般写成

when a const reference binds to a temporary, then the lifetime of that temporary is extended to the lifetime of the reference

我试图说明,虽然 Foo() 是临时的,但转换运算符返回的对 _x 的引用不是,上面的代码是不安全。

但输出似乎证明该示例安全的,临时Foo()的生​​命周期因存在对其之一的const引用而延长成员。

这样对吗?这在标准中的何处规定?

最佳答案

关于临时对象的一般规则是,当它们作为完整表达式的一部分结束时(非正式地,当到达 ; 时)它们的生命就结束了。

12.2 Temporary objects

3/ [...] Temporary objects are destroyed as the last step in evaluating the full-expression (1.9) that (lexically) contains the point where they were created. This is true even if that evaluation ends in throwing an exception. The value computations and side effects of destroying a temporary object are associated only with the full-expression, not with any specific subexpression.

关于c++ - 不是最重要的 const.. 但这是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8134347/

相关文章:

函数模板的 C++ Decltype

arrays - 使用 const 泛型将可变指针数组转换为可变引用

scheme - Racket:用一个函数改变两个常量

c++ - 使用结构方法返回时出错 - C++

c++ - 如何为类的每个实例创建实例特定方法?

c++ - boost 中的分位数函数 (C++)

c++ - 带有 std::ref 参数的 std::tie 和 std::make_tuple 有什么区别?

c++ - 将 const 引用传递到构造函数链中

c - 使用类对象宏是定义全局变量的好方法吗?

c# - 在静态类中使用常量