以下代碼摘錄自More Effective C++
auto_ptr.h
#ifndef AUTO_PTR_H
#define AUTO_PTR_H
template<typename T>
class auto_ptr
{
public :
//使用explicit關鍵字避免隐式轉換
explicit auto_ptr(T* p=0);
~auto_ptr();
//使用另一個類型相容的auto_ptr來初始化一個新的auto_ptr
template<typename U>
auto_ptr(auto_ptr<U>& rhs);
template<typename U>
auto_ptr<T>& operator=(auto_ptr<U>& rhs);
T& operator*() const;
T* operator->() const;
//傳回原始對象的指針
T* get() const;
//放棄指針的是以權
T* release();
//删除原有指針并獲得指針的p的所有權
void reset(T* p=0);
private:
T* pointee;
};
template<typename T>
auto_ptr<T>::auto_ptr(T* p)
:pointee(p)
{}
template<typename T>
template<typename U>
auto_ptr<T>::auto_ptr(auto_ptr<U>& rhs)
:pointee(rhs.release())
{}
template<typename T>
auto_ptr<T>::~auto_ptr()
{
delete pointee;
}
template<typename T>
template<typename U>
auto_ptr<T>& auto_ptr<T>::operator=(auto_ptr<U>& rhs)
{
if(this!=&rhs)
reset(rhs.release());
return *this;
}
template<typename T>
T& auto_ptr<T>::operator*() const
{
return *pointee;
}
template<typename T>
T* auto_ptr<T>::operator->() const
{
return pointee;
}
template<typename T>
T* auto_ptr<T>::get() const
{
return pointee;
}
template<typename T>
T* auto_ptr<T>::release()
{
T* oldpointee=pointee;
pointee=0;
return oldpointee;
}
template<typename T>
void auto_ptr<T>::reset(T* p)
{
if(pointee!=p)
{
delete pointee;
pointee=p;
}
}
#endif
用來測試的Item類
//Item.h
#ifndef ITEM_H
#define ITEM_H
class Item
{
public:
Item(void);
~Item(void);
void PrintContent() const;
};
#endif
//Item.cpp
using std::cout;
using std::endl;
Item::Item(void)
{
}
Item::~Item(void)
{
cout<<"Destorying....."<<endl;
}
void Item::PrintContent() const
{
cout<<"Here is the content"<<endl;
}
main.cpp
#include <iostream>
#include "auto_ptr.h"
#include "Item.h"
using std::cout;
int main()
{
auto_ptr<Item> itemPtr(new Item);
itemPtr->PrintContent();
auto_ptr<Item> itemPtr2(itemPtr);
itemPtr2->PrintContent();
return 0;
}
運作程式,可以看到建在堆上的Item對象自動釋放了,因為auto_ptr對象析構時将指針pointee delete了,同時結果如下:
Here is the content
Here is the content
Destorying.....
程式隻會輸出一句Destorying.....,因為在構造itemPtr2時,itemPtr的成員pointee指向的Item已經轉交給了itemPtr2中的指針,
是以最後隻會看到一句Destorying.....,也就是隻有一個Item對象析構了...
轉載于:https://www.cnblogs.com/-Lei/archive/2012/08/31/2664732.html