c++ - 全局变量的静态初始化是否在 `main()`之前完成?

标签 c++ multithreading language-lawyer

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 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.

考虑以下代码。

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/

相关文章:

c++ - 了解DEFER和OBSTRUCT宏

c - 函数指针的 uintptr_t/intptr_t 等价物?

C++ 宏扩展到函数体

c# - 从不可变对象(immutable对象)设置拷贝是否可以避免线程损坏?

ios - 我是否需要在 DispatchQueue.main.async 中使用 autoreleasepool block

c# - C#中的基本线程

c++ - 在 C/C++ 中的无符号左移之前屏蔽是否过于偏执?

c++ - 函数指针的模板参数推导(g++ & ICC vs Clang++ & VC++)

c++ - shared_ptr<const A> 到 shared_pointer<A>

C#-线程和父子传递