c++ - 如何正确注册?

标签 c++ static-members

我有一个工厂类来注册一个类型

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/

相关文章:

c++ - 有没有更快的方法在 OpenCV 中应用亮度?

c++ - 将 char 转换为 std::string,然后连接

c - 在另一个静态结构中静态分配结构成员?

java - 静态/类变量的值是如何传递的?

c# - 在设计时禁止绑定(bind)到静态属性

java - 为什么Java禁止内部类中的静态字段?

c# - 每当我调用该类时,我总是得到相同的 UIColor.White 返回值,而不是我请求的任何颜色

c++ - xutility(2227) : warning C4996: 'std::_Copy_impl'

c++ - constexpr如何推导值?

c++ - 测试是否安装了字体 (Win32)