考虑 [basic.start.static#2] 中的这个例子,它在 cppreference 中有更详细的解释
inline double fd() { return 1.0; }
extern double d1;
double d2 = d1; // unspecified:
// dynamically initialized to 0.0 if d1 is dynamically initialized, or
// dynamically initialized to 1.0 if d1 is statically initialized, or
// statically initialized to 0.0 (because that would be its value
// if both variables were dynamically initialized)
double d1 = fd(); // may be initialized statically or dynamically to 1.0
关于 d2
的动态初始化的前两个评论,这里毫无疑问。但是,它说 d2
的静态初始化是 0.0
,我想不通原因。由于标准没有指定 订购 静态初始化。换句话说,如果 d1
用于静态初始化 d2
,为什么d1
的值是在这一点上肯定为零?标准只说If constant initialization is not performed, a variable with static storage duration ([basic.stc.static]) or thread storage duration ([basic.stc.thread]) is zero-initialized ([dcl.init]). Together, zero-initialization and constant initialization are called static initialization; all other initialization is dynamic initialization. All static initialization strongly happens before ([intro.races]) any dynamic initialization.
最佳答案
An implementation is permitted to perform the initialization of a variable with static or thread storage duration as a static initialization even if such initialization is not required to be done statically, provided that
the dynamic version of the initialization does not change the value of any other object of static or thread storage duration prior to its initialization, and
the static version of the initialization produces the same value in the initialized variable as would be produced by the dynamic initialization if all variables not required to be initialized statically were initialized dynamically.
你知道如果
d1
和 d2
都是动态初始化的,然后 d1
被初始化为 0,所以如果 d1
是静态初始化的,应该初始化为0。
关于c++ - 为什么对象的静态初始化肯定为零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68720830/