boost库的scoped_ptr

#include<iostream>
#include<vld.h>
#include<memory>
#include<boost/smart_ptr.hpp>
using namespace std;
//using namespace boost;
template<typename T>
class scoped_ptr
{
private:
	scoped_ptr(const scoped_ptr<T> &);
	scoped_ptr<T>& operator = (const scoped_ptr<T> &);
public:
	explicit scoped_ptr(T *p = 0):px(p)
	{}
	~scoped_ptr()
	{
		delete px;
	}
public:
	T & operator*() const
	{
		assert(px != 0);
		return *px;
	}
	T * operator->() const
	{
		assert(px != 0);
		return px;
	}
	typedef scoped_ptr<T> this_type;
	void reset(T * p = 0)
	{
		assert(p==0 || p != px);
		this_type(p).swap(*this);//*this 即调用它的对象ps,this_type(p)构建了一个参数为p的无名对象
	}
	void swap(scoped_ptr & b)//交换两个指针的指向
	{
		T* tmp = b.px;
		b.px = px;
		px = tmp;
	}
private:
	T *px;


};
void main()
{
	int *p = new int(10);
	int *q = new int(100);
	scoped_ptr<int> ps(p);
	cout<<*ps<<endl;
	ps.reset(q);
	cout<<*ps<<endl;
	//scoped_ptr<int> ps1(ps);
}

猜你喜欢

转载自blog.csdn.net/qq_35353824/article/details/87972216