#ifndef HANDLE_H
#define HANDLE_H
#include <cstddef>
//泛型句柄类
template<typename T>
class Handle {
public:
Handle(T *p = 0):ptr(p), use(new std::size_t(1)) { }
Handle(const Handle &h):ptr(h.ptr), use(h.ptr) { ++*use; }
T& operator* ();
T* operator->();
const T& operator* () const;
const T* operator->() const;
Handle& operator = (const Handle&);
~Handle(){
rem_ref();
}
private:
T *ptr;
std::size_t *use;
void rem_ref()
{
if(--*use == 0){
delete ptr;
delete use;
}
}
};
template<typename T>
T& Handle<T>::operator*(){
if(ptr) return *ptr;
throw std::runtime_error
("dereference of unbound Handle");
}
template<typename T>
const T& Handle<T>::operator*() const {
if(ptr) return *ptr;
throw std::runtime_error
("dereference of unbound Handle");
}
template<typename T>
T* Handle<T>::operator->() {
if (ptr) return ptr;
throw std::runtime_error
("access throgh unbound Handle");
}
template<typename T>
const T* Handle<T>::operator->() const {
if (ptr) return ptr;
throw std::runtime_error
("access throgh unbound Handle");
}
template<typename T>
Handle<T>& Handle<T>::operator = (const Handle &rhs) {
++*rhs.use;
rem_ref();
ptr = rhs.ptr;
use = rhs.use;
return *this;
}
#endif