16.5 一个泛型句柄类
16.5.1 定义句柄类
#ifndef HANDLE_H
#define HANDLE_H
#include "stdafx.h"
#include
using namespace std;
template
class Handle{
public:
Handle(T *p=0):ptr(p), use(new size_t(1)){}
T& operator*();
T* operator->();
const T& operator*() const;
const T* operator->() const;
Handle(const Handle& h):ptr(h.ptr), use(h.use){++*use;}
Handle& operator=(const Handle&);
~Handle(){rem_ref();}
private:
T* ptr;
size_t *use;
void rem_ref(){
if(--*use==0){
delete ptr;
delete use;
}
}
};
template
inline Handle
++*rhs.use; // to avoid "i=i"
rem_ref();
ptr=rhs.ptr;
use=rhs.use;
return *this;
}
template
inline T& Handle
{
if(ptr) return *ptr;
throw std::runtime_error("dereference of unbound Handle");
}
template
inline T* Handle
{
if(ptr) return ptr;
throw std::runtime_error("dereference of unbound Handle");
}
#endif
#ifndef HANDLE_H
#define HANDLE_H
#include "stdafx.h"
#include
using namespace std;
template
class Handle{
public:
Handle(T *p=0):ptr(p), use(new size_t(1)){}
T& operator*();
T* operator->();
const T& operator*() const;
const T* operator->() const;
Handle(const Handle& h):ptr(h.ptr), use(h.use){++*use;}
Handle& operator=(const Handle&);
~Handle(){rem_ref();}
private:
T* ptr;
size_t *use;
void rem_ref(){
if(--*use==0){
delete ptr;
delete use;
}
}
};
template
inline Handle
++*rhs.use; // to avoid "i=i"
rem_ref();
ptr=rhs.ptr;
use=rhs.use;
return *this;
}
template
inline T& Handle
{
if(ptr) return *ptr;
throw std::runtime_error("dereference of unbound Handle");
}
template
inline T* Handle
{
if(ptr) return ptr;
throw std::runtime_error("dereference of unbound Handle");
}
#endif16.5.2 使用句柄
class Person{ 摘自 xufei96的专栏
Handle
{
Handle
cout<<*handle<<" "<<*hp2<
}
cout<<*handle<
{
Handle
cout<<*handle<<" "<<*hp2<
}
cout<<*handle<
#include "Handle.h"
class Age{
};
class Person{
private:
Handle
};
#include "Handle.h"
class Age{
};
private:
Handle
};