C++ 泛型句柄类

#include <iostream>
#include <stdexcept>
using namespace std;


template<class T> class handle
{
public:
	handle(T* p):use(new int(1)),ptr(p){}
	handle(handle& h)  //复制构造函数不需要考虑指针的移除问题,因为对象刚被新建,指针没有旧的指向,因此不需要释放之前的空间。
	{
		ptr = h.ptr;
		use = h.use;
		*use++;
	}

	T& operator*();
	const T& operator*() const; //const before ";"   
	T* operator->();
	const T* operator->() const;

	handle& operator=(const handle&);
	~handle(){ decrease(); }
private:
	int* use;
	T* ptr;
	void decrease()
	{
		if(!--*use)
		{
			delete ptr;
			delete use;
		}
	}
};

template<class T> handle<T>& handle<T>::operator=(const handle& h) //模版类成员函数,除了handle不用带<T>返回的handle& 也得带上<T>
{
	decrease();
	ptr = h.ptr;
	use = h.use;
	*use++;
	return *this;
}   

template<class T> T& handle<T>::operator*()
{
	if(ptr)
		return *ptr;
	else
		throw runtime_error("deference of unbound handle");
} 


template<class T> const T& handle<T>::operator*() const
{
	if(ptr)
		return *ptr;
	else
		throw runtime_error("deference of unbound handle");
}


template<class T> T* handle<T>::operator->()
{
	if(ptr)
		return ptr;
	else
		throw runtime_error("access throw unbound handle");
}



template<class T> const T* handle<T>::operator->() const
{
	if(ptr)
		return ptr;
	else
		throw runtime_error("access throw unbound handle");
}


class test
{
public:
	test(){}
	test(int i=0):t(i){}
	int t;
};          
int main()
{

	int tmp = 5;
	//错误写法 handle<int> h(&tmp);  //原因在于构造函数初始化计数为1,但是实际上有两个使用tmp的对象。
	//test 1
	handle<int> h(new int(5));
	cout<<*h<<endl;
	//test 2
	handle<test> h2(new test(10));
	cout<<(*h2).t<<endl;  //这里不能写为 *h2.t ,因为*没有. 的优先级高
	h2->t = 15;
	cout<<(*h2).t<<endl;
	//test 3
	// dont know how to use const version of * and -> operator
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值