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

Nuo*_*oji 3 c++ initialization static-order-fiasco c++14

想象一下这样的代码:

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

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

static bool Baz = [](){ registerFoo("baz", []() { return new BazFoo(); })}();
Run Code Online (Sandbox Code Playgroud)

而另一个:

static bool Bar = [](){ registerFoo("bar", []() { return new BarFoo(); })}();
Run Code Online (Sandbox Code Playgroud)

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

有没有办法让这个工作以安全的,独立于编译器的方式工作(对于c ++ 14)?

Bar*_*rry 10

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

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

您的注册功能可以通过:

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

这应该保证订购.