给定以下代码:
class foo
{
};
class bar: public foo
{
public:
~bar() { printf("~bar()\n"); }
};
class zab: public foo
{
public:
~zab() { printf("~zab()\n"); }
};
struct foo_holder
{
const foo &f;
};
int main()
{
foo_holder holder[]= { {bar()}, {zab()} };
printf("done!\n");
return 0;
}
输出是:
~bar()
~zab()
done!
C++0x 有一个子句规定,当用作新的初始化程序时,它可以创建悬空引用,但它没有说明(至少我找不到任何东西)关于使用临时变量的 const 引用的聚合初始化。
那么这是未指定的行为吗?
最佳答案
异常(exception)列表中没有提到它,因此应该延长临时的生命周期以匹配 foo_holder
s(数组)的生命周期。但是,这对我来说似乎是疏忽,也许提交缺陷报告可能是个好主意。
§12.2/5 规定,当引用绑定(bind)到临时对象时,临时对象的生命周期会延长以匹配引用的生命周期,并且因为 const foo& f
是 foo_holder
,引用的生命周期与 foo_holder
的生命周期匹配,根据 §3.7.5/1:
The storage duration of member subobjects, base class subobjects and array elements is that of their complete object (1.8).
这可能有点难以解释考虑引用,因为 §3.8/1 规定,对象的生命周期在存储被释放或重用时结束:
The lifetime of an object of type T ends when:
— if T is a class type with a non-trivial destructor (12.4), the destructor call starts, or
— the storage which the object occupies is reused or released.
但是,没有指定引用是否使用存储; §8.3.2/4 说
It is unspecified whether or not a reference requires storage (3.7).
也许对标准有更好了解的人会更了解这一点。
关于c++ - 临时绑定(bind)到聚合初始化结构成员的生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5719636/