我有一个工厂类来注册一个类型
class Factory
{
public:
template<class T>
static void regist()
{
mMap[T::type()] = [](){return new T();};
}
static Base* create(string type)
{
... // use map to find the function to create a new object
}
private:
static map<string, function<Base* ()>> mMap;
};
map<string, function<Base* ()>> Factory::mMap;
和 Base 的具体类 T
class A : public Base
{
public:
static string type() { return "A"; }
static bool sRegist;
A() {}
};
bool A::sRegist = []() -> bool {
Factory::regist<A>();
return true;
}();
但是,代码在运行时崩溃了。我认为这是由于静态成员的不确定初始化顺序。如何让它发挥作用?谢谢。
最佳答案
将 mMap
放在静态函数中,如下所示:
class Factory
{
public:
template<class T>
static void regist()
{
getMap()[T::type()] = [](){return new T();};
}
// ...
private:
static map<string, function<Base* ()>>& getMap() {
static map<string, function<Base* ()>> mMap;
return mMap;
}
};
在这种情况下,mMap
将在函数被调用时立即初始化。
关于c++ - 如何正确注册?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19338264/