是全局变量的静态初始化在`main()`之前完成? [英] Is the static initialization of global variables completed before `main()`?

查看:164
本文介绍了是全局变量的静态初始化在`main()`之前完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自C ++标准1998的一些相关摘录:

Some relevant excerpts from the C++ standard 1998:


具有静态存储持续时间的对象的存储应在任何其他初始化发生。具有常数表达式的零初始化和初始化统称为静态初始化;所有其他初始化都是动态初始化。 使用常量表达式初始化静态存储持续时间的POD类型的对象应在任何动态初始化之前初始化。在同一翻译单元的命名空间范围中定义并动态初始化的静态存储持续时间的对象应初始化

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.

它是由实现定义的,无论命名空间作用域的对象的动态初始化是否在之前完成 main 的第一个语句。如果初始化延迟到 main ,它应在首次使用与要初始化的对象相同的翻译单元中定义的任何函数或对象之前发生。

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()之后进行。我的问题是:是之前的全局变量 a 初始化为 1 / code>?然后,如果在输入 main()之后创建所有线程,则全局变量的静态初始化保证是线程安全的。

According to the standard, the static initialization takes place before the dynamic initialization, and the dynamic initialization may take place after main() is entered. My question is: is the global variable a initialized to be 1 before main() is entered? Then if all the threads are created after main() is entered the static initialization of global variables is guaranteed to be thread-safe.

推荐答案

标准说,在转换单元中调用任何函数之前,所有对象都在同一翻译单元(也就是对应于单个源文件的目标文件)中初始化。在你的例子中,它看起来像是在同一个文件,所以 a 将被初始化 main()

The standard says that all objects are initialized in the same translation unit (aka object file which corresponds to a single source file) before any function is called in that translation unit. In your example, it looks like they are in the same file, so a will be initialized before main() is called.

标准允许在运行时加载DLL的情况下进行延迟初始化。如果允许你的代码运行时链接,你不能说一切都在 main()之前初始化。

The standard is allowing lazy initialization to occur in the event that a DLL is loaded at run time. If you allow run-time linkage of your code, you can't say that everything is initialized before main().

这篇关于是全局变量的静态初始化在`main()`之前完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆