// ********************************************************************** // // Copyright (c) 2001 // Mutable Realms, Inc. // Huntsville, AL, USA // // All Rights Reserved // // ********************************************************************** #ifndef ICE_UTIL_HANDLE_H #define ICE_UTIL_HANDLE_H #include #include // // "Handle" or "smart pointer" class for classes derived from // IceUtil::Shared or IceUtil::SimpleShared. // namespace IceUtil { template class HandleBase { public: typedef T element_type; T* get() const { return _ptr; } T* operator->() const { if(!_ptr) { throw NullHandleException(__FILE__, __LINE__); } return _ptr; } operator bool() const { return _ptr ? true : false; } void swap(HandleBase& other) { std::swap(_ptr, other._ptr); } T* _ptr; }; template inline bool operator==(const HandleBase& lhs, const HandleBase& rhs) { T* l = lhs.get(); U* r = rhs.get(); if(l && r) { return *l == *r; } else { return !l && !r; } } template inline bool operator!=(const HandleBase& lhs, const HandleBase& rhs) { T* l = lhs.get(); U* r = rhs.get(); if(l && r) { return *l != *r; } else { return l || r; } } template inline bool operator<(const HandleBase& lhs, const HandleBase& rhs) { T* l = lhs.get(); U* r = rhs.get(); if(l && r) { return *l < *r; } else { return !l && r; } } template class Handle : public HandleBase { public: Handle(T* p = 0) { _ptr = p; if(_ptr) { _ptr->__incRef(); } } template Handle(const Handle& r) { _ptr = r._ptr; if(_ptr) { _ptr->__incRef(); } } #ifdef _WIN32 // COMPILERBUG: Is VC++ or GNU C++ right here??? template<> Handle(const Handle& r) #else Handle(const Handle& r) #endif { _ptr = r._ptr; if(_ptr) { _ptr->__incRef(); } } ~Handle() { if(_ptr) { _ptr->__decRef(); } } Handle& operator=(T* p) { if(_ptr != p) { if(p) { p->__incRef(); } if(_ptr) { _ptr->__decRef(); } _ptr = p; } return *this; } template Handle& operator=(const Handle& r) { if(_ptr != r._ptr) { if(r._ptr) { r._ptr->__incRef(); } if(_ptr) { _ptr->__decRef(); } _ptr = r._ptr; } return *this; } #ifdef _WIN32 // COMPILERBUG: Is VC++ or GNU C++ right here??? template<> Handle& operator=(const Handle& r) #else Handle& operator=(const Handle& r) #endif { if(_ptr != r._ptr) { if(r._ptr) { r._ptr->__incRef(); } if(_ptr) { _ptr->__decRef(); } _ptr = r._ptr; } return *this; } template static Handle dynamicCast(const HandleBase& r) { return Handle(dynamic_cast(r._ptr)); } template static Handle dynamicCast(Y* p) { return Handle(dynamic_cast(p)); } }; } #endif