c++ - 为什么对象的静态初始化肯定为零?

标签 c++ language-lawyer

考虑 [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.

最佳答案

[basic.start.static]/3:

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.


你知道如果 d1d2都是动态初始化的,然后 d1被初始化为 0,所以如果 d1是静态初始化的,应该初始化为0。

关于c++ - 为什么对象的静态初始化肯定为零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68720830/

相关文章:

c++ - 使用 ORB 描述符训练 svm?

c++ - std::map<std::vector<int>,double>> 中的 "Forced constness"?

c - 为什么 `p()` 和 `(*p)()` 都有效?

c++ - 内部编译器错误和 boost::bind

c++ - move 语义和对象类型参数

c++ - 如何从根文件夹及其所有子文件夹生成目录树?

c++ - std::function 中的冗余构造函数重载?

functional-programming - 什么是 "strongly moded"编程语言?

c - 将 0 个字节写入 NULL 指针是否安全?

c++ - 序列点和运算符优先级有什么区别?