閱讀714 返回首頁    go 京東網上商城


C++ 智能指針

C++ 智能指針

 

 

最近在做Windows上管理USB手機終端的相關程序。

 

實際情況:

Class Phone *symbian = new Phone();

Class ConnectManager, Class CommManager都需要對symbian指針進行引用和維護(保留一個拷貝)。

但是這樣就導致了symbian何時可以被delete?

在ConnectManager析構函數中delete? 這將導致CommManager無法使用symbian了。

在CommManager中delete symbian也是同樣的道理。

 

在參考了《C++ Primer》之後,自己動手寫一個智能指針

 

代碼如下

 

 

#include <iostream> using namespace std; class ConnectManager; class CommManager; class Phone { public: Phone() { cout << "Hello World!" << endl; } ~Phone() { cout << "Bye!" << endl; } }; 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 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); } 

 

 

 

運行結果如下:

 

Hello World!

ConnectManager: Hi I get the Phone

1 users

CommManager: Hi I get the Phone

2 users

CommManager: Can I delete the Phone?

No, You Can't. The Phone is in use;

1 users

ConnectManager: Can I delete the Phone?

Yes. You can

Bye!

 

 

代碼中已經注釋出來了。智能指針的關鍵是轉交數據的宿主。雖然Phone是給CommManager和ConnectManager使用,

但是,真正的Phone要由智能指針類去維護。

 

 

 

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

  上一篇:go 【zz】函數對象
  下一篇:go String,StringBuffer, StringBuilder 的區別