<menu id="w8yyk"><menu id="w8yyk"></menu></menu>
  • <dd id="w8yyk"><nav id="w8yyk"></nav></dd>
    <menu id="w8yyk"></menu>
    <menu id="w8yyk"><code id="w8yyk"></code></menu>
    <menu id="w8yyk"></menu>
    <xmp id="w8yyk">
    <xmp id="w8yyk"><nav id="w8yyk"></nav>
  • 網站首頁 > 物聯資訊 > 技術分享

    C++: 單例模式和缺陷

    2016-09-28 00:00:00 廣州睿豐德信息科技有限公司 閱讀
    睿豐德科技 專注RFID識別技術和條碼識別技術與管理軟件的集成項目。質量追溯系統、MES系統、金蝶與條碼系統對接、用友與條碼系統對接

    C++: 單例模式和缺陷

     

    實現一個單例模式

    1 class Singleton { 2     private: 3         Singleton() { cout << "Singleton::constructor" << endl; } 4         ~Singlton() { cout << "Singleton::destructor" << endl; } 5         Singleton(const Singleton&) {}; 6         Singleton &operator=(const Singleton&) {}; 7     public: 8         static Singleton* getInstance() { 9             if(m_aInstance == NULL) { 10                 m_aInstance = new Singleton(); 11             } 12             return m_aInstance; 13         } 14         void show() { 15             cout << "Singleton::show" << endl; 16         } 17     private: 18         static Singleton* m_aInstance; 19 }; 20   21 Singleton* Singleton::m_aInstance = NULL; 22   23 int main(int argc, char **argv) { 24     Singleton* aSingleton = Singleton::getInstance(); 25     aSingleton->show(); 26     return 0; 27 } 編譯執行上面的代碼,輸出如下:

     

    Singleton::constructor
    Singleton::show
    
    我們發現上面的輸出并沒有調用到Singleton的虛構函數,Singleton的資源可能沒有被釋放。現在的問題是要怎么才能在程序退出的時候正確釋放Singleton的資源。我們注意到這樣一個事實:

     

    系統會自動調用在棧和靜態數據區上分配的對象的析構函數來釋放資源。
    

    修改程序如下:

    1 class Singleton { 2     private: 3         Singleton() { cout << "Singleton::constructor" << endl; } 4         ~Singleton() { cout << "Singleton::destructor" << endl; } 5         Singleton(const Singleton&) {}; 6         Singleton &operator=(const Singleton&) {}; 7     public: 8         static Singleton* getInstance() { 9             if(m_aInstance == NULL) { 10                 m_aInstance = new Singleton(); 11             } 12             return m_aInstance; 13         } 14         void show() { 15             cout << "Singleton::show" << endl; 16         } 17   18     private: 19         class Garbage{ 20             public: 21                 ~Garbage() { 22                     if(m_aInstance != NULL) { 23                         delete m_aInstance; 24                     } 25                 } 26         }; 27       28     private: 29         static Singleton* m_aInstance; 30         static Garbage m_garbage; 31 }; 32   33 Singleton* Singleton::m_aInstance = NULL; 34 Singleton::Garbage Singleton::m_garbage; 35   36 int main(int argc, char **argv) { 37     Singleton* aSingleton = Singleton::getInstance(); 38     aSingleton->show(); 39     return 0; 40 } 編譯上面的代碼并執行,輸出如下:

     

    Singleton::constructor
    Singleton::show
    Singleton::destructor
    

    我們看到Singleton::destructor被明確的執行了。

    相關閱讀: 遞歸模板實現單例模式 RFID管理系統集成商 RFID中間件 條碼系統中間層 物聯網軟件集成
    最近免费观看高清韩国日本大全