在實際的c++項目中,常常會用new或malloc等在堆區申請動態資源,那麼極可能會忘記釋放資源。這個問題在程序量小的時候一通常不會發生,可是當程序量很大時,確是頗有可能發生。智能指針就是解決這一問題,讓指針能夠像對象同樣自動釋放。c++
解決思想:把全部指針抽象爲一個模板類,每個指針是一個具體的對象。在這個類中,有一個成員類用來控制計數。 1 class counter{spa
2 private: 3 int cnt; 4 T *ptr; 5 public: 6 friend class Smart_pointer; 7 counter(){ 8 cnt = 0; 9 ptr=NULL; 10 } 11 12 counter(counter& sp){ 13 cnt = 1; 14 counter = sp; 15 } 16 17 ~counter(){ 18 delete ptr; 19 } 20 21 }; 22 23 class Smart_pointer{ 24 private: 25 counter* pr; 26 27 public: 28 Smart_pointer(){ 29 30 pr = new counter(); 31 32 } 33 Smart_pointer(Smart_pointer &sp) 34 { 35 pr = new counter(sp); 36 } 37 Smart_pointer& operator =(Smart_pointer& sp) 38 { 39 ++sp->cnt;
--pr->cnt
if(pr->cnt==0)
delete pr;
pr = sp; 41 }
T operator *()
{
return *pr->ptr;
} 42 ~Smart_pointer()
{
--pr.cnt;
if(pr->cnt==0)
delete pr;
} 43 };