【发布时间】:2017-01-20 03:18:43
【问题描述】:
这是 invoking the copy constructor within the constructor 的衍生产品。
我相信一个对象已经完全形成,并且可以预期在初始化列表的末尾表现出这样的行为(编辑:虽然我错了!)。具体来说,成员函数和从构造函数本身访问本地状态的行为将与从任何其他成员函数完全相同。
虽然这似乎是一个有点争议的观点,但另一种选择是,只有在构造函数正常返回后,对象才完全形成。
下面是一个快速而肮脏的测试用例,它显示了初始化列表中提到的所有成员字段正在初始化以及那些没有被默认构造的字段。
#include <cstdio>
struct noise
{
noise() { printf("noise default constructed\n"); }
noise(int x) { printf("noise integer constructed %u\n", x); }
~noise() { printf("noise dtor\n"); }
};
struct invoke : public noise
{
noise init;
noise body;
invoke() : noise(3), init(4)
{
body = noise(5);
throw *this; // try to use the object before returning normally
}
~invoke() { printf("invoke dtor\n"); }
};
int main()
{
try
{
invoke i;
}
catch (...)
{
}
}
至少在我的机器上打印,
noise integer constructed 3
noise integer constructed 4
noise default constructed
noise integer constructed 5
noise dtor
noise dtor
noise dtor
noise dtor
invoke dtor
noise dtor
noise dtor
noise dtor
与往常一样,很难区分指定的作品和我的编译器实现的作品!这真的是UB吗?
【问题讨论】:
标签: c++ language-lawyer