第16章 模板与泛型编程(13)

2014-11-24 12:26:52 · 作者: · 浏览: 5

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& Handle::operator=(const Handle &rhs){
++*rhs.use; // to avoid "i=i"
rem_ref();
ptr=rhs.ptr;
use=rhs.use;
return *this;
}

template
inline T& Handle::operator*()
{
if(ptr) return *ptr;
throw std::runtime_error("dereference of unbound Handle");
}

template
inline T* Handle::operator->()
{
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& Handle::operator=(const Handle &rhs){
++*rhs.use; // to avoid "i=i"
rem_ref();
ptr=rhs.ptr;
use=rhs.use;
return *this;
}

template
inline T& Handle::operator*()
{
if(ptr) return *ptr;
throw std::runtime_error("dereference of unbound Handle");
}

template
inline T* Handle::operator->()
{
if(ptr) return ptr;
throw std::runtime_error("dereference of unbound Handle");
}

#endif16.5.2 使用句柄


Handle handle(new int(42));
{
Handle hp2=handle;
cout<<*handle<<" "<<*hp2< *hp2=10;
}
cout<<*handle< Handle handle(new int(42));
{
Handle hp2=handle;
cout<<*handle<<" "<<*hp2< *hp2=10;
}
cout<<*handle<


#include "Handle.h"
class Age{
};

class Person{
private:
Handle age;
};
#include "Handle.h"
class Age{
};

class Person{
private:
Handle age;
};

摘自 xufei96的专栏