gpt4 book ai didi

c++ - 当首先转换为引用类型时,临时对象仍然绑定(bind)到引用

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:03:14 26 4
gpt4 key购买 nike

为了更好地理解 C++ 标准而编译一些奇怪的代码时,我遇到了一个例子,我实际上不确定发生了什么。考虑一个简单的类,它在构造或析构时生成调试输出:

struct C {
C() { cout << "Constructed\t" << this << "\n"; }
C(const C& source) = delete;
C(C&&) = delete;
~C() { cout << "Destructed\t" << this << "\n"; }
};

现在是我不明白的代码:

int main()
{
const C& r = static_cast<const C&>(C());
cout << "Next line" << endl;
}

输出是(用 gcc 和 clang 试过):

Constructed 0x7fff6d6ebe60  
Next line
Destructed 0x7fff6d6ebe60

因此,正如您在此处看到的,临时对象被绑定(bind)到引用,即使它首先转换为引用类型。我不确定为什么会这样。我试着自己回答,这是我的想法:

  1. C()创建一个临时纯右值
  2. static_cast 5.2.9p4适用:

    Otherwise, an expression e can be explicitly converted to a type T using a static_cast of the form static_cast<T>(e) if the declaration T t(e); is well-formed, for some invented temporary variable t (8.5). The effect of such an explicit conversion is the same as performing the declaration and initialization and then using the temporary variable as the result of the conversion.

    因此创建了一个临时引用和static_cast的结果表达式是左值

  3. 接下来会发生什么以及为什么临时文件的生命周期会延长?它是否类似于临时绑定(bind)到临时引用,而临时引用本身又绑定(bind)到其他引用?

附言还尝试了这个(添加地址获取和取消引用运算符):

int main()
{
const C& r = *&static_cast<const C&>(C());
cout << "Next line" << endl;
}

gcc 的输出仍然是:

Constructed 0x7fffa1c50157
Next line
Destructed 0x7fffa1c50157

在这种情况下,当 clang 在“下一行”之前临时销毁时:

Constructed 0x7fff3374ab60
Destructed 0x7fff3374ab60
Next line

最佳答案

尝试查看标准的第 12.2/4 和 12.2/5 条:

  1. There are two contexts in which temporaries are destroyed at a different point than the end of the fullexpression. The first context is when a default constructor is called to initialize an element of an array. If the constructor has one or more default arguments, the destruction of every temporary created in a default argument is sequenced before the construction of the next array element, if any.

  2. 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: ...

这应该可以回答您的问题 - 为什么生命周期会延长。

关于c++ - 当首先转换为引用类型时,临时对象仍然绑定(bind)到引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26357392/

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