静态初始化顺序fiasco [英] static initialization order fiasco
问题描述
我从一本书中阅读关于SIOF的信息,并给出了一个例子:
I was reading about SIOF from a book and it gave an example :
//file1.cpp
extern int y;
int x=y+1;
//file2.cpp
extern int x;
int y=x+1;
现在我的问题是:
在上面的代码中, ?
1.在编译file1.cpp时,编译器保留y不变,即不为其分配存储。
2.编译器为x分配存储,但不会初始化它。
3.编译file2.cpp时,编译器将x保留为原样,即不为其分配存储空间。
4.编译器为y分配存储空间,但doesn
5.在链接file1.o和file2.o时,现在先让file2.o初始化,现在:
x的初始值为0 ?
Now My question is :
In above code..will following things happen ?
1. while compiling file1.cpp, compiler leaves y as it is i.e doesn't allocate storage for it.
2. compiler allocates storage for x, but doesn't initialize it.
3. While compiling file2.cpp, compiler leaves x as it is i.e doesn't allocate storage for it.
4. compiler allocates storage for y, but doesn't initialize it.
5. While linking file1.o and file2.o, now let file2.o is initialized first, so now:
Does x gets initial value of 0? or doesn't get initialized?
推荐答案
初始化步骤在3.6.2初始化非本地对象中给出C ++标准:
The initialization steps are given in 3.6.2 "Initialization of non-local objects" of the C++ standard:
步骤1: x
和 y
在任何其他初始化发生之前被初始化。
Step 1: x
and y
are zero-initialized before any other initialization takes place.
步骤2: x
或 y
- 哪一个没有规定的标准。该变量将获得值 1
,因为其他变量将被初始化为零。
Step 2: x
or y
is dynamically initialized - which one is unspecified by the standard. That variable will get the value 1
since the other variable will have been zero-initialized.
步骤3:其他变量将被动态初始化,获取值 2
。
Step 3: the other variable will be dynamically initialized, getting the value 2
.
这篇关于静态初始化顺序fiasco的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!