non-local-static 變數的初始化

來源:互聯網
上載者:User

標籤: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變數沒有存在的必要。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.