对此似乎没有简单的答案,但是关于何时可以访问静态类字段是否有任何可以安全地做出的假设?
编辑:唯一安全的假设似乎是在程序开始之前初始化所有静态变量(调用 main
)。所以,只要我不从其他静态初始化代码中引用静态,我就不用担心了吗?
最佳答案
该标准保证两件事 - 在同一个翻译单元(通常意味着 .cpp 文件)中定义的对象按照它们的定义顺序进行初始化(不是声明):
3.6.2
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.
另一件保证的事情是,翻译单元中静态对象的初始化将在使用此翻译单元中的任何对象或函数之前完成:
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.
我没有其他保证(特别是在不同翻译单元中定义的对象的初始化顺序是实现定义的)。
编辑
正如 Suma 的评论中所指出的,还保证它们在输入 main
之前被初始化。
关于c++ - 静态 C++ 类成员何时初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1421671/