您的位置:首页 > 编程语言 > C语言/C++

C++标准库---auto_ptr实现原理

2014-11-23 16:35 411 查看
auto_ptr是一个Template class,它的具体实现细节,可以参考以下:

//auto_ptr实做细目
#include<iostream>

using namespace std;

template<class T>
class my_auto_ptr
{
private:
	T* ap;
public:
	typedef T element_type;

	explicit my_auto_ptr(T* ptr=0) throw()
		:ap(ptr)
	{
	}

	//copy构造函数
	my_auto_ptr(my_auto_ptr& rhs) throw()
		:ap(rhs.release())
	{
	}
	
	template<class Y>
	my_auto_ptr(my_auto_ptr<Y>& rhs) throw()
		:ap(rhs.release())
	{
	}
	
	//赋值
	my_auto_ptr& operator=(my_auto_ptr& rhs) throw()
	{
		reset(rhs.release());
		return *this;
	}

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

	//析构函数
	~my_auto_ptr() throw()
	{
		delete ap;
	}

	//成员函数
	T* get() const throw()
	{
		return ap;
	}

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

	//重载 ->
	T* operator->() const 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;
		}
	}
};

template<class T>
ostream& operator<<(ostream& strm,const my_auto_ptr<T>&p)
{
	if(p.get()==NULL) 
	{
		strm<<"NULL";
	}
	else
	{
		strm<<*p;
	}
	return strm;
}

int main()
{
	my_auto_ptr<int> p;

	cout<<"p:"<<p<<endl;

	my_auto_ptr<int> q(new int(42));
	
	cout<<"q:"<<q<<endl;

	my_auto_ptr<int> s(q);//copy 转交控制权

	cout<<"q:"<<q<<endl;
	cout<<"s:"<<s<<endl;

	q=s;  //赋值  转交控制权
	cout<<"q:"<<q<<endl;
	cout<<"s:"<<s<<endl;

	system("pause");
	return 0;
}


运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: