这是我的问题的简化形式(基于一个真实的库):
// class template with static member variable:
template <typename T>
struct X
{
static std::vector<T> v_;
};
// definition of that static member variable:
template <typename T>
std::vector<T> X<T>::v_{};
// explicit instantiation of the class template:
template struct X<int>;
// library initialization function that fills v_ for X<int>:
static bool init()
{
X<int>::v_.reserve(1000);
...
return true;
}
// automatic initialization:
static bool initialized = init();
我的问题是,在这种情况下(单个翻译单元)是否可以保证——按照定义和实例化的顺序——在函数被调用X<int>::v_
之前被初始化。init()
AFAIK,静态变量按其定义的顺序在单个翻译单元中初始化,但是模板和显式实例化可以改变它吗?如果那个显式实例化被移除了怎么办?或者,放在源代码的末尾?