c++ - 在 C++ 中,我可以使用来自不同文件的值安全地初始化 unordered_map 吗?

标签 c++ initialization c++14 static-order-fiasco

想象一下这样的代码:

std::unordered_map<std::string, std::function<Foo *()>> FooFactory;
void registerFoo(std::string name, std::function<Foo *()> factory)
{
    FooFactory.emplace(name, factory);
}

如果我现在要在另一个文件中编写这样的代码:

static bool Baz = [](){ registerFoo("baz", []() { return new BazFoo(); })}();

还有一个:

static bool Bar = [](){ registerFoo("bar", []() { return new BarFoo(); })}();

在这种情况下,registerFoo 在程序初始化时被调用,但 FooFactory 随后被清零,因此注册的函数消失了。

有没有办法以一种安全的、独立于编译器的方式(对于 c++14)使它工作?

最佳答案

您可以将工厂本身放在一个函数中:

std::unordered_map<std::string, std::function<Foo *()>>& getFactory() {
    static std::unordered_map<std::string, std::function<Foo *()>> FooFactory;
    return FooFactory;
}

你的注册函数可以经过哪些:

void registerFoo(std::string name, std::function<Foo *()> factory)
{
    getFactory().emplace(name, factory);
}

这应该保证顺序。

关于c++ - 在 C++ 中,我可以使用来自不同文件的值安全地初始化 unordered_map 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45967503/

相关文章:

C++:int x[+30] 是有效的声明吗?

c# - 属性的默认值

c++ - QT - 只用键填充 QMap,然后为每个键添加值

c++ - 错误 : invalid use of void expression, C++

ruby - 在 `initialize` 方法之外声明一个实例变量

c++ - 这篇关于shared_ptr的use_count()的Standardese是什么意思?

c++ - 将新 C++ 转换为旧 C++

c++ - 类中动态分配的数组

c++ - C++ std::map 中对值的要求?

c++ - 避免并行递归异步算法中的递归模板实例化溢出