是否保证初始化顺序 [英] Is initialization order guaranteed
问题描述
我正在使用类似于以下代码部分的内容进行一些初始化。我知道 p< T> :: i _
的初始化是无序的。我相信 h
是有序的,所以我应该能够推断出它的初始化顺序。鉴于 p 在
h
的定义之前包括code>,是否可以保证 p< T> :: i _
将在 h
之前初始化?
I am using something like the following sections of code to do some initialization. I know that the initialization of p<T>::i_
is unordered. I believe that h
is ordered, so I should be able to reason about the order that it is initialized in. Given that the header for p
is included before the definition of h
, is there any guarantee that p<T>::i_
will be initialized before h
?
struct helper
{
template <typename T>
helper(const T&, int i)
{
p<T>::i_::push_back(i);
}
};
static helper h;
下面定义了类p。
template <typename T>
struct p
{
static std::vector<int> i_;
};
template <typename T>
std::vector<int> p<T>::i_;
推荐答案
具有静态存储持续时间的对象的初始化顺序为
The order of initialization of objects with static storage duration is undefined across translation units, and sequential within each translation unit.
在您的特殊情况下,情况更加复杂,因为具有静态存储的对象之一是对象的静态成员。模板类。实际上,这意味着访问成员 p< T> :: i _
的每个翻译单元将创建符号,并添加适当的初始化代码。稍后,链接器将选择其中一个实例并将其保留。即使看起来之前 h
中定义了 p< T> :: i _
您的翻译单元,您不知道链接器将保留哪个 p< T> :: i _
实例,并且该实例可能在另一个翻译单元中,并且
In your particular case things are more complicated, since one of the objects with static storage is a static member of a template class. What that means in a practical way is that each translation unit that accesses the member p<T>::i_
will create the symbol, and add the appropriate initialization code. Later the linker will pick one of the instances and keep it. Even if it looks like p<T>::i_
is defined before h
in your translation unit, you don't know which instance of p<T>::i_
will be kept by the linker, and that might be one in a different translation unit and thus the order is not guaranteed.
通常,拥有全局对象是一个坏主意,我建议您尝试在没有这些全局对象的情况下重新设计程序。
In general it is a bad idea to have global objects, I would suggest that you try to redesign your program without those globals.
这篇关于是否保证初始化顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!