gpt4 book ai didi

c++ - 显式实例化模板的静态成员和另一个静态变量的初始化顺序

转载 作者:行者123 更新时间:2023-12-03 07:15:28 24 4
gpt4 key购买 nike

这是我问题的简化形式(基于真实库):

// 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,静态变量按其定义顺序在单个转换单元中初始化,但是模板和显式实例化可以对其进行某些更改吗?如果删除了该显式实例怎么办?还是放在源代码的末尾?

最佳答案

[basic.start.dynamic]:

Dynamic initialization of a non-local variable with static storage duration is unordered if the variable is an implicitly or explicitly instantiated specialization, is partially-ordered if the variable is an inline variable that is not an implicitly or explicitly instantiated specialization, and otherwise is ordered.

[Note 1: An explicitly specialized non-inline static data member or variable template specialization has ordered initialization. — end note]


正如标准指出的那样, v_的初始化是 无序
但我们总是可以通过 static函数解决此问题:
template<typename T>
struct X{
static std::vector<T>& v_() noexcept {
static std::vector<T> v;
return v;
}
};
template struct X<int>;
static bool init(){
X<int>::v_().reserve(1000);
// ...
return true;
}
static bool initialized = init();

关于c++ - 显式实例化模板的静态成员和另一个静态变量的初始化顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64607718/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com