gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 18:29:46 28 4
gpt4 key购买 nike

这输出 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com