C++ 标准 1998 的一些相关摘录:
The storage for objects with static storage duration shall be zero-initialized before any other initialization takes place. Zero-initialization and initialization with constant expression are collectively called static initialization; all other initialization is dynamic initialization. Objects of POD types with static storage duration initialized with constant expressions 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 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 ofmain
, it shall occur before the first use of any function or object defined in the same translation unit as the object to be initialized.
考虑以下代码。
int a = 1;
int main()
{
cout << a << endl;
return 0;
}
按照标准,静态初始化发生在动态初始化之前,而动态初始化可能发生在进入main()
之后。我的问题是:在输入main()
之前,全局变量a
是否初始化为1
?然后如果所有线程都是在 main()
进入后创建的,那么全局变量的静态初始化保证是线程安全的。
最佳答案
标准规定,在翻译单元中调用任何函数之前,所有对象都在同一个翻译单元(也就是对应于单个源文件的目标文件)中初始化。在您的示例中,它们看起来像是在同一个文件中,因此 a
将在调用 main()
之前进行初始化。
该标准允许在运行时加载 DLL 的情况下进行延迟初始化。如果允许代码的运行时链接,则不能说所有内容都在 main()
之前初始化。
关于c++ - 全局变量的静态初始化是否在 `main()`之前完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25007701/