/* */ #ifndef _D_SHARED_HANDLE_H_ #define _D_SHARED_HANDLE_H_ #include template class SharedHandle { template friend std::ostream& operator<<(std::ostream& o, const SharedHandle& sp); template friend bool operator==(const SharedHandle& t1, const SharedHandle& t2); template friend bool operator!=(const SharedHandle& t1, const SharedHandle& t2); template friend bool operator<(const SharedHandle& t1, const SharedHandle& t2); private: T* obj; int* ucount; public: SharedHandle():obj(new T()), ucount(new int(1)) {} SharedHandle(T* obj):obj(obj), ucount(new int(1)) {} template SharedHandle(const SharedHandle& t):obj(t.get()), ucount(t.getRefCount()) { ++*ucount; } ~SharedHandle() { if(--*ucount == 0) { delete obj; delete ucount; } } template SharedHandle& operator=(const SharedHandle& t) { ++*t.getRefCount(); if(--*ucount == 0) { delete obj; delete ucount; } obj = t.get(); ucount = t.getRefCount(); return *this; } T* operator->() { return obj; } T* operator->() const { return obj; } T* get() const { return obj; } int* getRefCount() const { return ucount; } }; template std::ostream& operator<<(std::ostream& o, const SharedHandle& sp) { o << *sp.obj; return o; } template bool operator==(const SharedHandle& t1, const SharedHandle& t2) { return *t1.obj == *t2.obj; } template bool operator!=(const SharedHandle& t1, const SharedHandle& t2) { return *t1.obj != *t2.obj; } template bool operator<(const SharedHandle& t1, const SharedHandle& t2) { return *t1.obj < *t2.obj; } #endif // _D_SHARED_HANDLE_H_