1

我目前正在尝试解决静态初始化订单惨败。这是参考我之前的帖子 链接。我有一个填充静态容器属性的静态方法。现在我的项目中的一个类有一个静态属性,可以从该静态方法中检索一个值。问题是在启动静态方法之前调用类的静态属性。我的问题是如何解决这个问题。代码示例如下

//This is the code that has the static map container which is not initialized when 
//its queried by the OtherClass::mystring
Header File
class MyClass
{
    static std::map<std::string,std::string> config_map;
    static void SomeMethod();
};

Cpp File
std::map<std::string,std::string> MyClass::config_map ;

void MyClass::SomeMethod()
{
...
config_map.insert(std::pair<std::string,std::string>("dssd","Sdd")); //ERROR
}

现在,以下移植正在调用某些方法

 Header File
    class OtherClass
    {
        static string mystring;
    };

    Cpp File
    std::string OtherClass::mystring = MyClass::config_map["something"]; // However config_map has not been initialized.

谁能解释解决这种惨败的最佳方法是什么?我已经阅读了一些内容,但我仍然无法理解。任何建议或代码示例肯定会受到赞赏。

4

1 回答 1

1

声明一个函数并config_map在其中声明为静态

class MyClass {
...
  static std::map<std::string,std::string> & config_map() {
    static std::map<std::string,std::string> map;
    return map;
  }
};

void MyClass::SomeMethod()
{
...
config_map().insert(std::pair<std::string,std::string>("dssd","Sdd"));
}

std::string OtherClass::mystring = MyClass::config_map()["something"];

现在地图保证被初始化。

于 2013-05-12T03:17:16.620 回答