64,639
社区成员
发帖
与我相关
我的任务
分享
template <class 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.use){ ++*use; }
Handle& operator=(const Handle&);
~Handle() { rem_ref(); }
T& operator*();
T* operator->();
const T& operator*() const;
const T* operator->() const;
private:
T* ptr;
std::size_t *use;
void rem_ref();
};
template <class T>
inline Handle<T>& Handle<T>::operator=(const Handle &rhs)
{
++*rhs.use;
rem_ref();
ptr = rhs.ptr;
use = rhs.use;
return *this;
}
template <class T> inline T& Handle<T>::operator*()
{
if (ptr) {return *ptr;} ///
throw std::runtime_error("dereference of unbound Handle");
}
template <class T> inline T* Handle<T>::operator->()
{
if (ptr) {return ptr;} ///
throw std::runtime_error("access through unbound Handle");
}
template <class T> inline
const T& Handle<T>::operator*() const
{
if (ptr) {return *ptr;}
throw std::runtime_error("dereference of unbound Handle");
}
template <class T> inline
const T* Handle<T>::operator->() const
{
if (ptr) {return ptr;}
throw std::runtime_error("access through unbound Handle");
}
template <class T> inline
void Handle<T>::rem_ref()
{
if (--*use == 0)
{
delete ptr; delete use;
}
}
template <class T> inline T& Handle<T>::operator*()
{
if (ptr) {copy();return *ptr;} ///
throw std::runtime_error("dereference of unbound Handle");
}
template <class T> inline
Handle<T>& Handle<T>::copy() //写时复制???
{
if(!isOnly()) // 1 == *use
{
--*use;
ptr=new T(*ptr);
use=new std::size_t(1);
}
return *this;
}