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;
现在我的问题是:
在上面的代码中,会发生以下事情吗?
Now My question is :
In above code, will following things happen ?
- 在编译 file1.cpp 时,编译器将 y 保留原样,即不为其分配存储空间.
- 编译器为 x 分配存储空间,但不初始化它.
- 编译 file2.cpp 时,编译器将 x 保留原样,即不为其分配存储空间.
- 编译器为 y 分配存储空间,但不初始化它.
- 在链接file1.o和file2.o时,现在先初始化file2.o,所以现在:
x 的初始值是否为 0?还是没有初始化?
推荐答案
C++标准3.6.2非本地对象的初始化"给出了初始化步骤:
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.
第三步:动态初始化另一个变量,得到值2
.
Step 3: the other variable will be dynamically initialized, getting the value 2
.
这篇关于静态初始化命令惨败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:静态初始化命令惨败


- 近似搜索的工作原理 2021-01-01
- 从python回调到c++的选项 2022-11-16
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 静态初始化顺序失败 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- C++ 协变模板 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01