c++ - 静态类成员是否保证在调用 `main` 之前被初始化?

标签 c++ language-lawyer c++03

是否保证静态类成员在调用 main 之前被初始化?

最佳答案

我认为没有:

[C++03: 3.6.2/3]: It is implementation-defined whether or not the dynamic initialization (8.5, 9.4, 12.1, 12.6.1) 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.


嗯,真的

好吧,可以说,“在命名空间范围内定义”与“命名空间范围的对象”并不完全相同:

[C++03: 9.4.2/2]: The declaration of a static data member in its class definition is not a definition and may be of an incomplete type other than cv-qualified void. The definition for a static data member shall appear in a namespace scope enclosing the member's class definition. In the definition at namespace scope, the name of the static data member shall be qualified by its class name using the :: operator. The initializer expression in the definition of a static data member is in the scope of its class (3.3.6).

但是,initializer 在类的范围内;没有提到 static 成员本身具有命名空间范围以外的任何内容(除非我们在脑海中将词 “lexically” 注入(inject)各处)。

这个令人愉悦的段落:

[C++03: 9.4.2/7]: Static data members are initialized and destroyed exactly like non-local objects (3.6.2, 3.6.3).

然而,不幸的是,关于“非本地对象”,main 的顺序和静态初始化的唯一进一步定义是前面提到的 [C++03: 3.6 .2/3].


然后呢?

我相信 C++11 中的新措辞清楚地表明了这条原本可能模棱两可的规则的意图,它解决了所有问题:

[C++11: 9.4.2/6]: Static data members are initialized and destroyed exactly like non-local variables (3.6.2, 3.6.3).

[C++11: 3.6.2/4]: It is implementation-defined whether the dynamic initialization of a non-local variable with static storage duration is done before the first statement of main. [..]

关于c++ - 静态类成员是否保证在调用 `main` 之前被初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16300432/

相关文章:

c++ std将列表复制到 map

c++ - 在 xcode 中将 boost 库添加到 cocos2d-x 项目中?

c++ - 其可变参数没有参数的可变参数宏

c++ - 值初始化是否适用于原子对象?

c++ - 为什么 PRIu64 在此代码中不起作用?

c++ - 带有 std::vector 的模板 typedef 具有自定义分配器

c++ - InterfaceFileForASetTemplateClass

c++ - 你如何通过引用传递枚举?

c++ - 当基类的 POD 成员不打算由它初始化时,在调用其构造函数之前初始化它是否合法?

c++ - 二元运算符+重载的返回值是否应该是 const 并且它会干扰优化吗?