静态变量初始化顺序 [英] Static variables initialisation order

查看:129
本文介绍了静态变量初始化顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++保证编译单元(.cpp文件)中的变量按声明的顺序进行初始化。对于编译单元数,这个规则对每个单独的(我的意思是静态变量在类外)。



但是,变量的初始化的顺序是未定义的编译单元。



我在哪里可以看到关于gcc和MSVC的这个顺序的一些解释(我知道,依赖这是一个非常糟糕的主意 - 它只是为了理解

解决方案

正如你说的订单是



在同一个编译单元中,顺序是明确定义的:与定义相同的顺序。



这是因为这在语言级别但在链接器级别没有解决。所以你真的需要检查链接器文档。



对于gcc:查看 ld



我发现,即使改变被链接的对象文件的顺序也可以改变初始化顺序。所以它不仅仅是你的链接器,你需要担心,但如何链接器由你的构建系统调用。甚至尝试解决问题实际上是一个非启动。



这通常只是一个问题,当初始化全局引用对方在自己的初始化(所以只影响对象




    li>延迟初始化。

  • Schwarz计数器

  • 将所有复杂的全局变量放在同一个编译单元中。


C++ guarantees that variables in a compilation unit (.cpp file) are initialised in order of declaration. For number of compilation units this rule works for each one separately (I mean static variables outside of classes).

But, the order of initialization of variables, is undefined across different compilation units.

Where can I see some explanations about this order for gcc and MSVC (I know that relying on that is a very bad idea - it is just to understand the problems that we may have with legacy code when moving to new GCC major and different OS)?

解决方案

As you say the order is undefined across different compilation units.

Within the same compilation unit the order is well defined: The same order as definition.

This is because this is not resolved at the language level but at the linker level. So you really need to check out the linker documentation. Though I really doubt this will help in any useful way.

For gcc: Check out ld

I have found that even changing the order of objects files being linked can change the initialization order. So it is not just your linker that you need to worry about, but how the linker is invoked by your build system. Even try to solve the problem is practically a non starter.

This is generally only a problem when initializing global that reference each other during their own initialization (so only affects objects with constructors).

There are techniques to get around the problem.

  • Lazy initialization.
  • Schwarz Counter
  • Put all complex global variables inside the same compilation unit.

这篇关于静态变量初始化顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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