最小auto_ptr

template<class T>
class auto_ptr
{
	T* ap;
public:
	explicit auto_ptr(T* ptr = 0) throw():ap(ptr){}
	~auto_ptr()
	{
		delete ap;
		ap = 0;
	}
	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()//不用const是为了释放rhs
	{
		reset(rhs.release());
		return *this;
	}


	template<class Y>
	auto_ptr& operator=(auto_ptr<Y>& rhs) throw()
	{
		reset(rhs.release());
		return *this;
	}


	T& operator *() const throw()
	{
		return *ap;
	}


	T* operator->()const throw()
	{
		return ap;
	}


	T* get() throw()
	{
		return ap;
	}


	T* release() throw()
	{
		T* tmp(ap);
		ap = 0;
		return tmp;
	}


	void reset(T* ptr = 0) throw()
	{
		if ( ap != ptr ) {
			delete ap;
			ap = ptr;
		}
	}


};


你可能感兴趣的:(最小auto_ptr)