静态 C++ 类成员何时初始化?
对此似乎没有简单的答案,但是否可以安全地做出关于何时可以访问静态类字段的假设?
There appears to be no easy answer to this, but are there any assumptions that can be safely made about when a static class field can be accessed?
唯一安全的假设似乎是在程序开始之前初始化所有静态变量(调用 main
).所以,只要我不从其他静态初始化代码中引用静态,我就不用担心了吗?
The only safe assumption seems to be that all statics are initialized before the program commences (call to main
). So, as long as I don't reference statics from other static initialization code, I should have nothing to worry about?
推荐答案
该标准保证了两件事 - 在同一个翻译单元(通常是 .cpp 文件)中定义的对象按照它们的定义顺序进行初始化(不是声明):
The standard guarantees two things - that objects defined in the same translation unit (usually it means .cpp file) are initialized in order of their definitions (not declarations):
3.6.2
在进行任何其他初始化之前,具有静态存储持续时间 (basic.stc.static) 的对象的存储应进行零初始化 (dcl.init).零初始化和用常量表达式初始化统称为静态初始化;所有其他初始化都是动态初始化.具有使用常量表达式 (expr.const) 初始化的静态存储持续时间的 POD 类型 (basic.types) 的对象应在任何动态初始化发生之前进行初始化.在同一翻译单元的命名空间范围内定义的静态存储持续时间并动态初始化的对象应按照其定义在翻译单元中出现的顺序进行初始化.
The storage for objects with static storage duration (basic.stc.static) shall be zero-initialized (dcl.init) before any other initialization takes place. Zero-initialization and initialization with a constant expression are collectively called static initialization; all other initialization is dynamic initialization. Objects of POD types (basic.types) with static storage duration initialized with constant expressions (expr.const) shall be initialized before any dynamic initialization takes place. Objects with static storage duration defined in namespace scope in the same translation unit and dynamically initialized shall be initialized in the order in which their definition appears in the translation unit.
另一件保证的事情是,翻译单元中静态对象的初始化将在使用此翻译单元中的任何对象或函数之前完成:
The other guaranteed thing is that initialization of static objects from a translation unit will be done before use of any object or function from this translation unit:
命名空间范围对象的动态初始化(dcl.init, class.static, class.ctor, class.expl.init)是否在main的第一条语句之前完成是实现定义的.如果初始化延迟到 main 的第一个语句之后的某个时间点,它应该发生在与要初始化的对象在同一翻译单元中定义的任何函数或对象的第一次使用之前.
It is implementation-defined whether or not the dynamic initialization (dcl.init, class.static, class.ctor, class.expl.init) of an object of namespace scope is done before the first statement of main. If the initialization is deferred to some point in time after the first statement of main, it shall occur before the first use of any function or object defined in the same translation unit as the object to be initialized.
我没有其他保证(特别是在不同翻译单元中定义的对象的初始化顺序是实现定义的).
Nothing else i guaranteed (especially order of initialization of objects defined in different translation units is implementation defined).
编辑正如 Suma 的评论中所指出的,还保证它们在输入 main
之前被初始化.
EDIT
As pointed in Suma's comment, it is also guaranteed that they are initialized before main
is entered.
相关文章