プログラミング言語C++ 第3版に記載されている物とほとんど同じです。
#ifndef _HANDLE_H_ #define _HANDLE_H_ template<class X> class Handle { X *rep; int *pcount; public: X* operator->() {return rep;} X* Get() {return rep;} Handle(): rep(0), pcount(new int(1)) {} Handle(X* pp): rep(pp), pcount(new int(1)) {} Handle(const Handle& r) : rep(r.rep), pcount(r.pcount) {(*pcount)++;} Handle& operator=(const Handle& r) { if( rep == r.rep ) return *this; if( --(*pcount) <= 0 ) { delete rep; delete pcount; } rep = r.rep; pcount = r.pcount; (*pcount)++; return *this; } bool operator==(const Handle& r) { return rep == r.rep; } ~Handle() { if(--(*pcount) <= 0) {delete rep; delete pcount;} }; }; #endif