You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

该方案能否解决C++静态初始化顺序问题?

静态std::vector的初始化安全问题

假设有一个静态std::vector,程序启动时会自动向其中添加内容,但这里存在初始化顺序问题——可能在vector完成初始化前就调用push_back:

inline std::vector<const char*> my_vector;

int register_type(const char* name)
{
    static int id_counter = 0;
    my_vector.push_back(name);
    return id_counter++;
}
inline int my_type_1 = register_type("my_type_1");

虽然从标准层面,inline静态变量会按出现顺序初始化,所以这段代码技术上可行,但绝非好方案——如果从其他头文件或cpp文件调用register_type,这个初始化顺序的保证就失效了。

于是我尝试把vector改成指针,想在首次使用时完成初始化:

static inline std::unique_ptr<std::vector<const char*>> p_to_types;

int register_type(const char* name)
{
    static bool bHasBeenInitialised = false;
    static int id_counter = 0;

    if (!bHasBeenInitialised)
    {
        p_to_types = std::make_unique<std::vector<const char*>>();
        bHasBeenInitialised = true; 
    }   
    p_to_types->push_back(name);

    return id_counter++;
}

inline int my_type_1 = register_type("my_type_1");

这样确实能保证vector在首次使用前完成初始化,但std::unique_ptr本身的初始化还是会执行,如果它的初始化发生在vector初始化之后,会把指针置空,所以这个方案根本解决不了问题。

我知道常用的解决办法是把vector作为函数内的静态变量,但这样每次访问vector时都会产生一个检查是否初始化的分支。


内容的提问来源于stack exchange,提问作者Zebrafish

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 05:33:11