gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 22:28:24 25 4
gpt4 key购买 nike

是否保证静态类成员在调用 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 initializerexpression 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com