auto_ptr 源码

template <typename _Tp>
class auto_ptr
{
private:
	_Tp *m_ptr;
public:
	typedef _Tp elementType;

	// object life cycle
	explicit auto_ptr(elementType *p) throw():m_ptr(p)
	{
	}

	auto_ptr(auto_ptr &a) throw():m_ptr(a.release())
	{
	}

	template <typename _Tp1>
	auto_ptr(auto_ptr<_Tp1> &a) throw() : m_ptr(a.release())
	{
	}

	auto_ptr& operator= (auto_ptr& a) throw()
	{
		reset(a.release());
		return *this;
	}

	template <typename _Tp1>
	auto_ptr& operator=(auto_ptr<_Tp1> &a) throw()
	{
		reset(a.release());
		return *this;
	}

	~auto_ptr()
	{
		delete m_ptr;
	}

	// operator override
	elementType& operator*() const throw()
	{
		assert(m_ptr != 0);
		return *m_ptr;
	}

	elementType* operator->() const throw()
	{
		assert(m_ptr != 0);
		return m_ptr;
	}

	// helper 
	elementType* get() const throw()
	{
		return m_ptr;
	}

	elementType* release() throw()
	{
		elementType *tmp = m_ptr;
		m_ptr = 0;
		return tmp;
	}

	void reset(elementType *p = 0) throw()
	{
		if (p != m_ptr)
		{
			delete m_ptr;
			m_ptr = p;
		}
	}
};

 

你可能感兴趣的:(auto_ptr 源码)