绑定到成员初始值设定项列表中的引用成员的临时对象的生命周期 (C++14)
Lifetime of a temporary object bound to a reference member in member initializer list (C++14)
我在 cppreference.com 上查找 lifetime of a temporary,我发现了一些从 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 开始,临时绑定到引用成员的生命周期将延长到对象的生命周期?
我试过下面的代码 GCC and 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 都会在我尝试过的每个版本上对您的代码发出警告,我认为这是符合要求的,但理想情况下它们应该在那里出错。
我在 cppreference.com 上查找 lifetime of a temporary,我发现了一些从 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 开始,临时绑定到引用成员的生命周期将延长到对象的生命周期?
我试过下面的代码 GCC and 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 都会在我尝试过的每个版本上对您的代码发出警告,我认为这是符合要求的,但理想情况下它们应该在那里出错。