且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

什么时候初始化静态 C++ 类成员?

更新时间:2021-06-30 01:40:16

该标准保证了两件事 - 在同一个翻译单元(通常意味着 .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.