全局变量按照出现在翻译模块中的顺序进行初始化,不同翻译模块中变量初始化的相对顺序未指定(所谓“静态初始化顺序惨败”)。
命名空间对此有影响吗?例如,如果我有这个代码:
//first.cpp
int first;
int second;
与这段代码相比,初始化顺序会有什么不同吗:
//second.cpp
namespace {
int first;
}
int second;
是否存在将全局对象放入命名空间会影响初始化顺序的情况?
最佳答案
3.6 Other non-local variables with static storage duration have ordered initialization. Variables with ordered initialization defined within a single translation unit shall be initialized in the order of their definitions in the translation unit.
命名空间对此没有影响 - 本节未提及。
影响顺序的是不同的翻译单元。如果您需要定义它们之间的顺序,请使用诸如 GCC 的 constructor
属性之类的扩展。
关于c++ - 命名空间会影响 C++ 中的初始化顺序吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8353414/