天天看點

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;

u_ptr(phone *ph): use(0), pphone(ph) { }

~u_ptr() { delete pphone; }

private:

phone *pphone;//這裡是關鍵,轉移資料的宿主

size_t use;

class connectmanager

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;

u_ptr *puptr;

class commmanager

commmanager(u_ptr *p): puptr(p)

cout << "commmanager: hi i get the phone" << endl;

~commmanager()

cout << "commmanager: can i delete the phone" << endl;

cout << "no, you can't. the phone is in use" << endl;

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;

connectmanager: can i delete the phone?

yes. you can

bye!

代碼中已經注釋出來了。智能指針的關鍵是轉交資料的宿主。雖然phone是給commmanager和connectmanager使用,

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