C ++ 11:std ref全局变量和非函数本地thread_local初始化顺序? [英] C++11: std ref global variable and non-function-local thread_local initialization order?

查看:269
本文介绍了C ++ 11:std ref全局变量和非函数本地thread_local初始化顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在非静态初始化阶段,在非主要构造函数的C ++ 11中的全局变量被构造。



同样,非函数本地thread_local变量是在每个线程thread_local初始化阶段期间构造的。



C ++ 11标准规定了这些变量应该以什么顺序构造?在这两种情况下,如果有两个变量:

  //全局范围

A :: A ){bf(); } //构造函数使用全局b

A a;
B b;

C ++ 11标准规定了它们应该被初始化的顺序,

同样,对于非函数本地thread_local, >  //全局范围

A :: A(){bf(); } //一个构造函数使用全局b

thread_local A a;
thread_local B b;

标准是否指定必须构造的顺序,在初始化之前是从另一个的构造函数中使用的?



您可以提供 C ++ 11标准引用

解决方案

您的声明:使用非平凡构造函数创建C ++ 11中的全局变量之前在静态初始化阶段进入主。似乎不完全是真的 - 它们可能不会被初始化直到动态初始化阶段



对于有序初始化的变量,你的第一个a和b,那么标准表示


在单个
翻译单元中定义的有序初始化的变量应按照它们的
在翻译单元中的定义。


3.6.2 / 2涵盖了所有这一切。



编辑:就我可以告诉你的第二个a和b没有有序的初始化,并可以按任何顺序初始化。但我可能会缺少一些东西。


Global variables in C++11 with non-trivial constructors are constructed before the entry to main during a static initialization phase.

Likewise non-function-local thread_local variables are constructed during a per-thread "thread_local initialization phase".

Does the C++11 standard specify in what order these variables shall be constructed? In both cases if there are two variables:

// global scope

A::A() { b.f(); }  // A constructor uses global b

A a;
B b;

Does the C++11 standard specify in what order they shall be initialized, or that an error should be produced if a variable is used uninitialized?

Likewise for non-function-local thread_local:

// global scope

A::A() { b.f(); }  // A constructor uses global b

thread_local A a;
thread_local B b;

Does the standard specify the order they must be constructed, and does it define what will happen if the variable is used from the constructor of another before it is initialized?

Can you please provide a C++11 standard reference in support of any claims you make to have an answer.

解决方案

Your statement that "Global variables in C++11 with non-trivial constructors are constructed before the entry to main during a static initialization phase." doesn't seem to be entirely true - they may not be initialised until the dynamic initialization phase

For variables with "ordered initialization", which your first a and b are, then the standard says

Variables with ordered initialization defined within a single translation unit shall be initialized in the order of their definitions in the translation unit.

3.6.2/2 covers all this.

Edit: as far as I can tell your second a and b don't have ordered initialization, and could be initialized in either order. But I may be missing something.

这篇关于C ++ 11:std ref全局变量和非函数本地thread_local初始化顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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