gpt4 book ai didi

c++ - const 引用是否绑定(bind)到另一个从临时悬挂引用转换而来的引用?

转载 作者:可可西里 更新时间:2023-11-01 16:06:10 27 4
gpt4 key购买 nike

下面是代码片段:

#include <iostream>
using namespace std;
struct B{
int b;
~B(){cout <<"destruct B" << endl;}
};
B func(){
B b;
b.b = 1;
return b;
}
int main(){
const B& instance = (const B&)func(); //is `instance` a dangling reference?
cout <<instance.b<<endl;
return 0;
}

this online compiler输出是

destruct B
destruct B
1

因此返回值似乎比 cout 操作更早析构。所以 instance 似乎是一个悬空引用。

如果我们把const B& instance = (const B&)func();改成const B& instance =func();,那么结果就是

destruct B
1
destruct B

作为补充,如果我在vs2015中测试代码,那么输出的是最后一个。但是,如果在 gcc(before 4.6) 中测试,输出是前者,但在4.6之后的版本是后者。所以我想知道是在线编译器错误还是引用悬空。

最佳答案

根据最新稿[class.temporary]/6 (不相关的部分被我删掉了):

The third context is when a reference is bound to a temporary object. The temporary object to which the reference is bound or the temporary object that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference if the glvalue to which the reference is bound was obtained through one of the following:

  • ...

  • a const_­cast ([expr.const.cast]), static_­cast ([expr.static.cast]), dynamic_­cast ([expr.dynamic.cast]), or reinterpret_­cast ([expr.reinterpret.cast]) converting, without a user-defined conversion, a glvalue operand that is one of these expressions to a glvalue that refers to the object designated by the operand, or to its complete object or a subobject thereof,

  • ...

... [ Note: An explicit type conversion ([expr.type.conv], [expr.cast]) is interpreted as a sequence of elementary casts, covered above. [ Example:

const int& x = (const int&)1;  // temporary for value 1 has same lifetime as x

— end example ] — end note ]

您的代码格式正确。


在C++14之前,标准中对这种情况的表述不明确,存在缺陷问题1376 .此问题阐明了在这种情况下不应延长临时对象的生命周期。但是,此说明已被问题 1299 取代(其解决方案甚至不包含在 C++17 中,而是包含在当前草案中)。

所以可以断定issue 1299解决前是GCC 4.6以后的bug。还有一个bug report 52202对于海湾合作委员会。

关于c++ - const 引用是否绑定(bind)到另一个从临时悬挂引用转换而来的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50542643/

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