#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
}
C++ 泛型句柄类
最新推荐文章于 2024-07-27 22:35:43 发布