C++的auto_ptr所做的事情,就是動態分配對象以及當對象不再需要時自動執行清理。
使用std::auto_ptr,要#include <memory>。
基本介紹
- 中文名:自動指針
- 外文名:auto_ptr
代碼
template<class T>class auto_ptr{private: T*ap;public: //constructor & destructor-----------------------------------(1) explicit auto_ptr(T*ptr=0)throw():ap(ptr) { } ~auto_ptr()throw() { delete ap; } //Copy & assignment--------------------------------------------(2) auto_ptr(auto_ptr& rhs)throw():ap(rhs.release()) { } template<class Y> auto_ptr(auto_ptr<Y>&rhs)throw():ap(rhs.release()) { } auto_ptr& operator=(auto_ptr&rhs)throw() { reset(rhs.release()); return*this; } template<class Y> auto_ptr& operator=(auto_ptr<Y>&rhs)throw() { reset(rhs.release()); return*this; } //Dereference----------------------------------------------------(3) T& operator*()const throw() { return*ap; } T* operator->()const throw() { returnap; } //Helper functions------------------------------------------------(4) //value access T* get()const throw() { returnap; } //release owner ship T* release()throw() { T*tmp(ap); ap=0; return tmp; } //reset value void reset(T*ptr=0)throw() { if(ap!=ptr) { deleteap; ap=ptr; } } //Special conversions-----------------------------------------------(5) template<class Y> struct auto_ptr_ref { Y*yp; auto_ptr_ref(Y*rhs):yp(rhs){} }; auto_ptr(auto_ptr_ref<T>rhs)throw():ap(rhs.yp) { } auto_ptr& operator=(auto_ptr_ref<T>rhs)throw() { reset(rhs.yp); return*this; } template<class Y> operator auto_ptr_ref<Y>()throw() { returnauto_ptr_ref<Y>(release()); } template<class Y> operator auto_ptr<Y>()throw() { returnauto_ptr<Y>(release()); }};