閱讀90 返回首頁    go 技術社區[雲棲]


warning C4150: 刪除指向不完整“XXX”類型的指針;沒有調用析構函數

 

情況源於我的之前一片博客《C++ 智能指針》,在我寫demo代碼的時候。

 

向前申明了class Phone, 然後再U_ptr類析構函數中delete Phone的指針。

出現warning C4150: 刪除指向不完整“XXX”類型的指針;沒有調用析構函數

 

 

這個waring會導致內存泄露。前向申明的類的析構函數沒有被調用

 

 

出現warning的代碼如下:

 

#include <iostream> using namespace std; class ConnectManager; class CommManager; class Phone; class U_ptr { friend class ConnectManager; friend class CommManager; public: U_ptr(Phone *pH): use(0), pPhone(pH) { } ~U_ptr() { delete pPhone; } private: Phone *pPhone; size_t use; }; class Phone { public: Phone() { cout << "Hello World!" << endl; } ~Phone() { cout << "Bye!" << endl; } }; class ConnectManager { public: ConnectManager(U_ptr *p): pUptr(p) { ++pUptr->use; cout << "ConnectManager: Hi I get the Phone" << endl; cout << pUptr->use << " users" << endl; } ~ConnectManager() { cout << "ConnectManaer: Can I delete the Phone?" << endl; if (--pUptr->use == 0) { cout << "Yes, You can" << endl; delete pUptr; } else { cout << "No, You can't, The Phone is in use" << endl; cout << pUptr->use << " users" << endl; } } private: U_ptr *pUptr; }; class CommManager { public: CommManager(U_ptr *p): pUptr(p) { ++pUptr->use; cout << "CommManager: Hi I get the Phone" << endl; cout << pUptr->use << " users" << endl; } ~CommManager() { cout << "CommManager: Can I delete the Phone" << endl; if (--pUptr->use == 0) { cout << "Yes, You can" << endl; } else { cout << "No, You can't. The Phone is in use" << endl; cout << pUptr->use << " users" << endl; } } private: U_ptr *pUptr; }; int main(void) { Phone *symbian = new Phone(); U_ptr *pU = new U_ptr(symbian); ConnectManager connManager = ConnectManager(pU); CommManager commManager = CommManager(pU); }  

 

 

出現原因:

 

class Phone;這種方式向前申明,其後麵的類隻能申明其指針,前向申明以後的類無法看到其類實體。

 

所以,delete的時候,Phone的析構函數對後麵的類是透明不可見的,除非使用頭文件包含。

最後更新:2017-04-02 06:51:38

  上一篇:go C++ State 設計模式
  下一篇:go VC調節音量