c++ - 绑定(bind)到成员初始值设定项列表中的引用成员的临时对象的生命周期 (C++14)

标签 c++ reference c++14 temporary-objects

我正在查找 lifetime of a temporary在 cppreference.com 上,我发现了一些与 C++14 不同的东西:

Whenever a reference is bound to a temporary or to a base subobject of a temporary, the lifetime of the temporary is extended to match the lifetime of the reference, with the following exceptions:

...

a temporary bound to a reference member in a constructor initializer list persists only until the constructor exits, not as long as the object exists. (note: such initialization is ill-formed as of DR 1696) (until C++14)

我查了一下标准,确实没有这样的说法。 ($12.2/5 临时对象 [class.temporary])

这是否意味着从 C++14 开始,临时绑定(bind)到引用成员的生命周期将延长到对象的生命周期?

我用 GCC 尝试了以下代码和 CLANG两者似乎都不是,临时将在构造函数结束时被销毁。

#include <iostream>

struct X {
    ~X() { std::cout << "X dtor\n"; }
};
struct Y {
    Y() : x_(X()) { std::cout << "Y ctor\n"; }
    const X& x_;
    ~Y() { std::cout << "Y dtor\n"; }
};
int main()
{
    Y y;
    std::cout << "Hello, world!\n";
}

结果:

Y ctor
X dtor
Hello, world!
Y dtor

我是不是理解错了?

最佳答案

您引用的缺陷报告已被采纳,N4582 已将新措辞包含在[class.base.init] 中:

A temporary expression bound to a reference member in a mem-initializer is ill-formed. [Example:

struct A {
  A() : v(42) { }  // error
  const int& v;
};

— end example ]

因此它不会延长对象的生命周期 - 代码只是格式错误。 gcc 和 clang 都会在我尝试过的每个版本上对您的代码发出警告,我认为这是符合要求的,但理想情况下它们应该在那里出错。

关于c++ - 绑定(bind)到成员初始值设定项列表中的引用成员的临时对象的生命周期 (C++14),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37549377/

相关文章:

c++ - lambda 是如何 move 的?

C++ 不需要的类型推导

c++ - opencv 3.1 的静态库在哪里

c++ - 插入动态数组

javascript - JavaScript 中的引用问题?

C++ 函数练习 - 不断返回零

c++ - 如何避免与 `asio::ip::tcp::iostream` 的数据竞争?

c++ - 在命名空间中定义一个类

c++ - TCHAR[]、LPWSTR、LPTSTR 和 GetWindow 文本函数

java - 在 Java 中转换引用变量