C++標準程序庫提供的auto_ptr是一種智能型指針,幫助程序員防止”被異常拋出時發生資源泄漏“。
1、auto_ptr的初始化
template <class _Tp> class auto_ptr {
private:
_Tp* _M_ptr;
public:
typedef _Tp element_type;
explicit auto_ptr(_Tp* __p = 0) __STL_NOTHROW : _M_ptr(__p) {}
auto_ptr(auto_ptr& __a) __STL_NOTHROW : _M_ptr(__a.release()) {}
#ifdef __STL_MEMBER_TEMPLATES
template <class _Tp1> auto_ptr(auto_ptr<_Tp1>& __a) __STL_NOTHROW
: _M_ptr(__a.release()) {}
#endif /* __STL_MEMBER_TEMPLATES */
上面是STL源代碼中class auto_ptr定義的一部分,由上面可以看出一般指針的初始化式不適應於auto_ptr。
auto_ptr可能的初始化式如下:
std::auto_ptr<ClassA> ptr1(new ClassA);//OK
std::auto_ptr<ClassA> ptr2(ptr1);//OK
std::auto_ptr<ClassA> ptr3 = new ClassA;//ERROR
2、auto_ptr的所有權問題
C++標準程序庫中規定了一個對象只能被一個auto_ptr對象擁有。
std::auto_ptr<ClassA> ptr1(new ClassA);
std::auto_ptr<ClassA> ptr2(ptr1);//ptr1不再擁有new出來的ClassA對象,所有權轉移給ptr2
這點在將auto_ptr作爲參數轉遞給函數時尤爲重要,因爲這樣會導致原來的auto_ptr不再所有之前的對象,後期如果有針對該對象的類的操作,就會發生錯誤。
void fun(std::auto_ptr<ClassA> p)
{
//do-something
}
int main()
{
std::auto_ptr<ClassA> ptr(new ClassA);
fun(ptr);//當fun運行時,ptr已經不再擁有new出來的ClassA
//do-something on ptr
//這時如果再在ptr上操作就會發生錯誤
}
3、使用const 限定符來禁止所有權的轉移
將auto_ptr加上const限定符後對象的所有權就不能再轉移了。另外需要指出的是這裏的關鍵詞只是說明不能更改auto_ptr的擁有權,但是可是更改其所擁有的對象。
void fun(const std::auto_ptr<ClassA> p)
{
//do-something
}
int main()
{
const std::auto_ptr<ClassA> ptr(new ClassA);
fun(ptr);//當fun運行時,ptr仍然擁有new出來的ClassA
//do-something on ptr
//這時繼續操作ptr就不會出錯
ClassA m;
*ptr = m;//可以改ptr所擁有的對象
}