码迷,mamicode.com
首页 > 编程语言 > 详细

【c++】模拟实现boost库里的scoped_ptr

时间:2015-07-17 12:01:02      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:

//模拟实现boost下的scoped_ptr

#include <iostream>
#include <assert.h>
using namespace std;

template <class T>
class scoped_ptr
{
private:
	T * px;

	scoped_ptr(scoped_ptr const &);
	scoped_ptr& operator=(scoped_ptr const &);


	void operator==(scoped_ptr const &)const;
	void operator!=(scoped_ptr const &)const;
public:
	scoped_ptr(T *p = 0) :px(p)
	{}

	//从auto_ptr获得指针的管理权
	scoped_ptr(std::auto_ptr<T> p) :px(p.release())
	{}

	~scoped_ptr()
	{
		delete px;
	}

	// 删除原来的指针,保存新的指针
	void reset(T * p = 0)
	{
		assert(p == 0 || p != px);
		scoped_ptr<T>(p).swap(*this);
	}

	T& operator*()const
	{
		assert(px != 0);
		return *px;
	}

	T* operator->()const
	{
		assert(px != 0);
		return px;
	}

	T* get()const
	{
		return px;
	}

	void swap(scoped_ptr & b)
	{
		T *tmp = b.px;
		b.px = px;
		px = tmp;
	}
};

int main()
{
	int *p = new int(10);
	scoped_ptr<int> ptr(p);
	cout << *ptr << endl;
	return 0;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

【c++】模拟实现boost库里的scoped_ptr

标签:

原文地址:http://blog.csdn.net/zhaoyaqian552/article/details/46924997

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!