这段代码会产生未定义的行为还是仅仅是未指定的行为?
假设我们有两个编译单元,如下所示:
// a.cpp
extern int value2;
int value1 = value2 + 10;
// b.cpp
extern int value1;
int value2 = value1 + 10;
当我在 VC2010 上尝试时,它首先将 value1
和 value2
初始化为零。 value1
和 value2
不是都是动态初始化的并且默认初始化不适用于它们吗?
谢谢,
Lets say that we have two compilation units as follows:
// a.cpp
extern int value2;
int value1 = value2 + 10;
// b.cpp
extern int value1;
int value2 = value1 + 10;
When I tried it on VC2010, it initializes value1
and value2
to zero first. aren't both value1
and value2
dynamically initialized and default initialization doesn't apply on them?
Thanks,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
3.6.2/1 规定“具有静态存储持续时间(3.7.1)的对象应在发生任何其他初始化之前进行零初始化(8.5)”。
所以你是对的,它们没有默认初始化。但它们是零初始化的,这实际上对于 int 来说是一样的。对于类类型来说,这不一定是同一件事。
也就是说,我并不承诺这里的行为仅仅是初始化的顺序未指定,因此一个变量最终为 10,另一个变量为 20,但未指定哪个是哪个。它可能因其他原因而未定义,但我想不出任何原因。
3.6.2/1 says that "Objects with static storage duration (3.7.1) shall be zero-initialized (8.5) before any other initialization takes place".
So you're right, they aren't default-initialized. But they are zero-initialized, which in fact for
int
is the same thing. For a class type it's not necessarily the same thing.That said, I'm not promising the behavior here is merely that the order of initialization is unspecified, and hence that one variable ends up as 10 and the other 20, but unspecified which is which. It might be undefined on some other grounds, but I can't think of any.
在所有其他初始化发生之前,每个全局变量首先被零初始化。
3.6.2 [basic.start.init] / 2
中描述了此行为:(这是来自 C++0x FDIS,但我相信 C++98 标准也是这么说的。)
Every global variable is first zero-initialized, before every other initializations happen.
This behaviour is described under
3.6.2 [basic.start.init] / 2
:(This is from the C++0x FDIS, but I believe the C++98 standard says the same.)