First look at a piece of code:
///////////////////////////////////////////////////// class Single{Public : Single(); Static Single* S_INST; Staticstd:: Map<int, int> S_map;}; Single* S_inst = new Single;std:: Map<int, int>Single ::S_map;Single::single() {s_map[4] =6;}
The above code can be compiled using both MinGW492 and VS2008, but will report errors when running. is an error when using MinGW492:
原因就在于类Single中有两个静态成员变量static Single* s_inst;staticstd::map<int, int> s_map;
Static variables must be initialized before entering the main function.
The sequence of initialization of static variables is consistent with the order in which they are defined, regardless of the order in which they are declared .
The order of the definitions is:
new Single;std::map<int, int> Single::s_map;
Therefore, the single constructor is entered, and the S_map is inserted in the single constructor, and S_map is not initialized at this time.
So the modification method is also very simple, modify the order of the static variable definition:
///////////////////////////////////////////////////// class Single{Public : Single(); Static Single* S_INST; Staticstd:: Map<int, int> S_map;};//S_map before S_inststd:: Map<int, int>Single ::S_map; Single* S_inst = new Single;Single::single() {s_map[4] =6;}
To say more, this article does not discuss the singleton pattern, the case of a single example is later written.
C + + compiled successfully, failed to run the static variable