简体   繁体   English

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

[英]Lifetime of a temporary object bound to a reference member in member initializer list (C++14)

I'm looking up lifetime of a temporary on cppreference.com and I found something changed from C++14: 我在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) (注意:从DR 1696开始这样的初始化是不正确的)(直到C ++ 14)

I checked the standard there's really no such statement. 我检查了标准,真的没有这样的说法。 ($12.2/5 Temporary objects [class.temporary]) ($ 12.2 / 5临时物品[class.temporary])

Does it mean from C++14 the lifetime of a temporary bound to a reference member will be extended to the object's lifetime? 这是否意味着从C ++ 14开始,临时绑定到引用成员的生命周期将扩展到对象的生命周期?

I've tried the following code with GCC and CLANG both seem not, the temporary will be destroyed when constructor ends. 我尝试了以下代码与GCCCLANG似乎都没有,临时将被构造函数结束时销毁。

#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";
}

result: 结果:

Y ctor
X dtor
Hello, world!
Y dtor

Do I misunderstand it? 我误解了吗?

The defect report you cited has been adopted, and N4582 already includes the new wording in [class.base.init] : 您引用的缺陷报告已被采用,N4582已在[class.base.init]中包含新的措辞:

A temporary expression bound to a reference member in a mem-initializer is ill-formed. 绑定到mem-initializer中的引用成员的临时表达式格式不正确。 [Example: [例:

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

— end example ] - 结束例子]

So it's not extended for the object's lifetime - the code is simply ill-formed. 所以它没有扩展到对象的生命周期 - 代码只是格式不正确。 gcc and clang both emit warnings on your code on every version I've tried, which I think is conforming but ideally they should error there. gcc和clang都会在我尝试的每个版本上对你的代码发出警告,我认为这符合要求,但理想情况下它们应该在那里出错。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM