標籤:style blog color div ar c++ file har
non-local-static 變數,包括global對象、定義於namespace範圍內的對象,classes內、以及在file範圍內被聲明為static的對象,不包括在函數內的static變數。由於c++對不同編譯單元non-local-static 變數的初始化順序沒有規定,如果這些non-local-static變數之間存在相互依賴,則被依賴的變數可能沒有完全初始化。如
//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;}
輸出結果0。
說明Month::Feb並未初始化。因為Month::Feb和m_test都是non-local-static變數,定義在不同的編譯單元中,而m_test依賴於Month::Feb,而Month::Feb並未初始化,這樣的程式存在風險。
怎麼辦,把non-local-static 變數變為local-static變數,並返回該變數,需要變數時調用函數即可,如下
static Month Jan(){ return Month(1); }static Month Fet(){ return Month(2);}
總之,一句話,所有的static變數(包括全域變數)全部放在函數內定義,即都定義為local-static變數。non-local-static變數沒有存在的必要。