第16章 模板与泛型编程(13)
16.5 一个泛型句柄类
16.5.1 定义句柄类
#ifndef HANDLE_H
#define HANDLE_H
#include "stdafx.h"
#include <iostream>
using namespace std;
template<class T>
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<class T>
inline Handle<T>& Handle<T>::operator=(const Handle &rhs){
++*rhs.use; // to avoid "i=i"
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("dereference of unbound Handle");
}
#endif
#ifndef HANDLE_H
#define HANDLE_H
#include "stdafx.h"
#include <iostream>
using namespace std;
template<class T>
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<class T>
inline Handle<T>& Handle<T>::operator=(const Handle &rhs){
++*rhs.use; // to avoid "i=i"
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("dereference of unbound Handle");
}
#endif16.5.2 使用句柄
Handle<int> handle(new int(42));
{
Handle<int> hp2=handle;
cout<<*handle<<" "<<*hp2<<endl; //42 42
*hp2=10;
}
cout<<*handle<<endl; //10
Handle<int> handle(new int(42));
{
Handle<int> hp2=handle;
cout<<*handle<<" "<<*hp2<<endl; //42 42
*hp2=10;
}
cout<<*handle<<endl; //10使用Handle对象对指针进行使用计数
#include "Handle.h"
class Age{
};
class Person{
private:
Handle<Age> age;
};
#include "Handle.h"
class Age{
};
class Person{
private:
Handle<Age> age;
};
摘自 xufei96的专栏
补充:软件开发 , C++ ,