// ********************************************************************** // // Copyright (c) 2003-2004 ZeroC, Inc. All rights reserved. // // This copy of Ice is licensed to you under the terms described in the // ICE_LICENSE file included in this distribution. // // ********************************************************************** #ifndef ICE_UTIL_HANDLE_H #define ICE_UTIL_HANDLE_H #include #include // // "Handle" or "smart pointer" class for classes derived from // IceUtil::GCShared, 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; } 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) { this->_ptr = p; if(this->_ptr) { this->_ptr->__incRef(); } } template Handle(const Handle& r) { this->_ptr = r._ptr; if(this->_ptr) { this->_ptr->__incRef(); } } #ifdef _WIN32 // COMPILERBUG: Is VC++ or GNU C++ right here??? template<> Handle(const Handle& r) #else Handle(const Handle& r) #endif { this->_ptr = r._ptr; if(this->_ptr) { this->_ptr->__incRef(); } } ~Handle() { if(this->_ptr) { this->_ptr->__decRef(); } } Handle& operator=(T* p) { if(this->_ptr != p) { if(p) { p->__incRef(); } T* ptr = this->_ptr; this->_ptr = p; if(ptr) { ptr->__decRef(); } } return *this; } template Handle& operator=(const Handle& r) { if(this->_ptr != r._ptr) { if(r._ptr) { r._ptr->__incRef(); } T* ptr = this->_ptr; this->_ptr = r._ptr; if(ptr) { ptr->__decRef(); } } 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(this->_ptr != r._ptr) { if(r._ptr) { r._ptr->__incRef(); } T* ptr = this->_ptr; this->_ptr = r._ptr; if(ptr) { ptr->__decRef(); } } 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