I am currently trying to resolve a static initialization order fiasco. This is in reference to my previous post link . I have a static method that populates the properties of a static container. Now one class in my project has a static property that retrieves a value from that static method. The problem is the static property of the class is called before the static method is initiated. My question is how can I resolve this issue. The code example is given below
//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
}
Now some method is being called by the following porting
Header File
class OtherClass
{
static string mystring;
};
Cpp File
std::string OtherClass::mystring = MyClass::config_map["something"]; // However config_map has not been initialized.
Could anyone explain whats the best method to resolve such a fiasco ? I have done some reading but I still cant understand it. Any suggestions or code example would definitely be appreciated.
declare a function and declare config_map
as a static inside it
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"];
now map is guarantee to be initialized.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.