Non-local-static variables, including global objects, objects defined in the namespace scope, objects declared as static within the classes, and objects in the file scope, static variables not included in the function. C ++ does not specify the initialization sequence of non-local-static variables of different compilation units. If these non-local-static variables are mutually dependent, the dependent variables may not be fully initialized. For example
//Month.hclass Month{public: ~Month(void); static Month Jan; static Month Feb; explicit Month(int a); int val;};//Month.cpp#include "Month.h"Month Month::Feb(2);Month Month::Jan(1);Month::Month(int a):val(a){}Month::~Month(void){}//MonthTest.h#include "Month.h"class MonthTest{public: MonthTest(void); ~MonthTest(void); Month month;};//MonthTest.cpp#include "MonthTest.h"MonthTest::MonthTest(void):month(Month::Feb){}MonthTest::~MonthTest(void){}MonthTest m_test;//mainextern MonthTest m_test ;int _tmain(int argc, _TCHAR* argv[]){ cout << m_test.month.val <<endl; getchar(); return 0;}
The output result is 0.
Description month: Feb is not initialized. Because both month: Feb and m_test are non-local-static variables and are defined in different compilation units, m_test depends on month: Feb, and month: Feb is not initialized, such a program has risks.
What to do? Change the non-local-static variable to the local-static variable and return the variable. You can call the function when you need the variable, as shown below:
static Month Jan(){ return Month(1); }static Month Fet(){ return Month(2);}
In a word, all static variables (including global variables) are defined in the function, that is, all are defined as local-static variables. The non-local-static variable does not exist.