乱序初始化成员 - 这样可以吗?
来自对此答案的评论:
类成员按顺序初始化的声明。按照这个逻辑,下面的构造函数应该调用未定义的行为:
struct Foo
{
Bar a;
Bar b;
Foo(Bar c) : a(b = c) { }
};
显然,我们在初始化 a
之前首先分配给 b
。分配给未初始化的对象应该是UB。代码与 Bar = int
一起“工作”并不奇怪,但如果我将 Bar
设为带有构造函数的重类,我会看到 b
确实在 a
之前初始化。
(为了更加疯狂,我们甚至可以说 Foo(Bar c, Bar d) : a(b = c), b(d) { }
,仍然没有任何警告。)
然而 GCC 4.6.1没有对此发出警告。这是可以接受的、定义明确的行为,还是完全错误的?
From a comment on this answer:
Class members are initialized in their order of declaration. By this logic, the following constructor should invoke undefined behaviour:
struct Foo
{
Bar a;
Bar b;
Foo(Bar c) : a(b = c) { }
};
Patently, we are assigning to b
first before a
has been initialized. Assigning to an uninitialized object should be UB. It's not surprising that the code "works" with Bar = int
, but if I make Bar
a heavy class with constructors, I see that b
does indeed get initialized before a
.
(For extra lunacy, we can even say Foo(Bar c, Bar d) : a(b = c), b(d) { }
, still with no warning.)
Yet GCC 4.6.1 doesn't warn about this. Is this acceptable, well-defined behaviour, or is this strictly wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
给定一个
Bar
,其中非初始化状态实际上对赋值运算符很重要,我收到来自 GCC 的警告:test: https://ideone.com/VDZzG
不过,我尝试过的其他编译器似乎并不关心......
Given a
Bar
where non-initialized state actually matters to the assignment operator, I get warnings from GCC:test: https://ideone.com/VDZzG
Other compilers I've tried don't seem to care, though...