初始化列表中的依赖关系
这种行为定义明确吗?
class Foo
{
int A, B;
public:
Foo(int Bar): B(Bar), A(B + 123)
{
}
};
int main()
{
Foo MyFoo(0);
return 0;
}
Is this behavior well-defined?
class Foo
{
int A, B;
public:
Foo(int Bar): B(Bar), A(B + 123)
{
}
};
int main()
{
Foo MyFoo(0);
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,它是未定义的。
A
将首先被初始化(它位于类定义中的第一个),并且它使用未初始化的B
。类成员按照它们在类定义中出现的顺序进行初始化,而不管它们在初始化列表中的顺序如何。事实上,将成员定义顺序与初始化列表顺序不匹配是不好的做法。
如果您的
Foo
实例碰巧具有静态持续时间,例如Foo f(0); int main(){}
,行为是明确定义的。具有静态持续时间的对象在发生任何其他初始化之前进行零初始化;在这种情况下,当构造函数运行时,A
和B
将为 0。不过,之后的行为是相同的:先是A
,然后是B
,为A
赋予值 123,为B
赋予值。 code> 的值是Bar
(还是丑陋的)。No, it's undefined.
A
will be initialized first (it's first in the class definition), and it uses uninitializedB
.Class members are initialized in the order they appear in the class definition, irrespective of their order in the initialization list. Indeed, it is bad practice to mismatch the member definition order with the initialization list order.
If your instance of
Foo
happened to have static duration, like inFoo f(0); int main(){}
, the behavior is well-defined. Objects with static duration are zero-initialized before any other initialization takes place; in that case,A
andB
will be 0 when the constructor is run. After that, though, the behavior is the same: firstA
thenB
, givingA
a value of 123 andB
a value ofBar
(still ugly).不,初始化顺序是由类本身的声明顺序定义的。
来自 C++ 标准
12.6.2 [class.base.init] p5
:No, initialization order is defined by the declaration order in the class itself.
From the C++ standard
12.6.2 [class.base.init] p5
:初始化是按照声明中出现的顺序完成的,而不是按照您在构造函数中编写的顺序完成的。
看看这个问题,有点相似:
初始化器列表*参数*评估顺序
Initialization is done in the order of appearance in the declaration, not the order you write it in the constructor.
Look at this question, it's somewhat similar:
Initializer list *argument* evaluation order