Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

C++ 中被冷落的 auto_ptr 智能指針深度解析

先拋三個問題:

1:C++ 能不能自動釋放記憶體?
 
2:C++ 的智能指針究竟怎麼實作出來的?
 
3:下面這段程式碼,註解拿掉與留著,結果會有什麼不同?

#include<iostream>
#include<memory>
#include<new>
using namespace std;
void * operator new(size_t size,int data,char *flags)
{
 return ::operator new(size);
}
void operator delete(void *tmp)
{
  cout<<"delete"<<endl;
  free(tmp);
}
int main()
{
 int *tmp=new (10,NULL)int[10];
 //auto_ptr<int> pInt(tmp);
 return 0;
}

申請記憶體之後最常被遺忘的動作就是回收。寫 C/C++ 的人多半都記得 new 要配 delete、malloc 要配 free(其實 new/delete 未必真的配置與釋放記憶體,原因可另參我先前寫的關於 new 運算子一文)。那麼 C++ 有沒有自動回收的機制?有的。

答案就是 auto_ptr。有人從沒聽過,有人嫌它功能不足而轉投 Boost。身為 C++ 的內建特性,還是有必要理解與分析一次——工程師本來就懶,釋放記憶體這種事就交給它吧。

MSDN 對它的描述是:

Wraps a smart pointer around a resource that ensures the resource is destroyed automatically when control leaves a block.

意思是:它是一個資源智能指針,當資源不再被使用時,能自動把佔用的記憶體釋放掉。原始碼定義在 <memory> 中:

template<class _Ty>
 class auto_ptr {
public:
 typedef _Ty element_type;
 explicit auto_ptr(_Ty *_P = 0) _THROW0(): _Owns(_P != 0), _Ptr(_P) {}
 auto_ptr(const auto_ptr<_Ty>& _Y) _THROW0()
  : _Owns(_Y._Owns), _Ptr(_Y.release()) {}
 auto_ptr<_Ty>& operator=(const auto_ptr<_Ty>& _Y) _THROW0()
  {if (this != &_Y)
   {if (_Ptr != _Y.get())
    {if (_Owns)
     delete _Ptr;
    _Owns = _Y._Owns; }
   else if (_Y._Owns)
    _Owns = true;
   _Ptr = _Y.release(); }
  return (*this); }
 ~auto_ptr()
  {if (_Owns)
   delete _Ptr; }
 _Ty& operator*() const _THROW0()
  {return (*get()); }
 _Ty *operator->() const _THROW0()
  {return (get()); }
 _Ty *get() const _THROW0()
  {return (_Ptr); }
 _Ty *release() const _THROW0()
  {((auto_ptr<_Ty> *)this)->_Owns = false;
  return (_Ptr); }
private:
 bool _Owns;
 _Ty *_Ptr;
 };

可以確定的是:智能指針靠模板實作,這也是唯一可行的路——泛型。

兩個資料成員

 bool _Owns;//代表該智能指針是否擁有這份資源
 _Ty *_Ptr;//指向記憶體中已配置的資源

建構式

explicit auto_ptr(_Ty *_P = 0) _THROW0(): _Owns(_P != 0), _Ptr(_P) {}

配置成功時 _P 不為 0,於是 _Ptr 指向該資源,並把擁有權標記為真。

拷貝建構式

 auto_ptr(const auto_ptr<_Ty>& _Y) _THROW0()
  : _Owns(_Y._Owns), _Ptr(_Y.release()) {}

結論很明確:一份資源只能由一個智能指針擁有。拷貝發生時,原本持有者會透過 _Y.release() 交棒;若讓兩個智能指針同時擁有,釋放時必然出錯。

 _Ty *release() const _THROW0()
  {((auto_ptr<_Ty> *)this)->_Owns = false;//不再擁有該資源,並回傳資源指標
  return (_Ptr); }

解構式(最關鍵)

 ~auto_ptr()
  {if (_Owns)
   delete _Ptr; }

誰擁有,誰負責釋放。

賦值運算子

auto_ptr<_Ty>& operator=(const auto_ptr<_Ty>& _Y) _THROW0()
{if (this != &_Y)//先排除自己賦值給自己
{if (_Ptr != _Y.get())//再判斷是否指向同一份資源
{if (_Owns)//指向不同資源時,先釋放原本持有的資源
delete _Ptr;
_Owns = _Y._Owns; }
else if (_Y._Owns)//指向同一資源時,標記擁有權
_Owns = true;
_Ptr = _Y.release(); }//解除 _Y 的擁有權並取回指標
return (*this); }

三個簡單的存取函式

 _Ty& operator*() const _THROW0()
  {return (*get()); }
 _Ty *operator->() const _THROW0()
  {return (get()); }
 _Ty *get() const _THROW0()
  {return (_Ptr); }

最後看一個已加註解的例子,這裡用 printf 而非 cout,原因留給讀者想想:

#include<iostream>
#include<memory>
#include<new>
using namespace std;
//重載的 new
void * operator new(size_t size,int data,char *flags)
{
 return ::operator new(size);
}
//重載的 delete
void operator delete(void *tmp)
{
  cout<<"delete"<<endl;
  free(tmp);
}
int main()
{
 int *tmp=new (10,NULL)int[10];//呼叫重載的 new
 *tmp=5;
 auto_ptr<int> pInt(tmp);
 auto_ptr<int> pTmp(pInt);
 printf("%d\n",*pTmp);
 //cout<<*pTmp<<endl;//為什麼不用 cout?可以自己想想
 return 0;//釋放時會呼叫重載的 delete
}

Copyright © Linux教程網 All Rights Reserved