1 #if !defined(__SUIT_SMARTPTR_H)
2 #define __SUIT_SMARTPTR_H
6 class SUIT_EXPORT RefCount {
9 RefCount() : crefs( 0 ) {}
11 RefCount( const RefCount& ) : crefs( 0 ) {}
13 virtual ~RefCount() {}
14 // operator= (does not change counter)
15 RefCount& operator=( const RefCount& ) { return *this; }
17 // increments reference counter
22 // decrements reference counter
25 if ( crefs > 0 && --crefs == 0 )
29 // get reference counter value
30 int refcount() const { return crefs; }
33 unsigned long crefs; // reference counter
36 template <class T> class SmartPtr {
38 // default constructor
39 SmartPtr() : p( 0 ) {}
40 // constructor from any RefCount-based class
41 template<class Y> SmartPtr( Y* y_ ) { p = dynamic_cast<T*>( y_ ); if ( p ) p->upcount(); }
42 // copy constructor from any RefCount-based class
43 template<class Y> SmartPtr( const SmartPtr<Y>& y_ ) { p = dynamic_cast<T*>( y_.get() ); if ( p ) p->upcount(); }
45 SmartPtr( const SmartPtr& t_ ) : p( t_.p ) { if ( p ) p->upcount(); }
47 virtual ~SmartPtr(void)
54 //operator RefCount*() { return (RefCount*)p; }
55 T& operator*() const { return *p; }
56 T* operator->() const { return p; }
57 operator T*() const { return p; }
58 T* get() const { return p; }
61 template<class Y> SmartPtr& operator=( const SmartPtr<Y>& y_ )
63 if ( this == &y_) return *this;
64 return operator=( y_.get() );
66 SmartPtr& operator=( const SmartPtr& t_ )
68 if ( this == &t_) return *this;
69 return operator=( t_.get() );
71 SmartPtr& operator=( T* p_ )
82 int operator==( const SmartPtr& t_ ) { return p == t_.p; }
83 int operator==( const T* p_ ) { return p == p_; }
84 friend int operator==( const T* p_, const SmartPtr& t_ ) { return t_ == p_; }
85 int operator!=( SmartPtr& t_ ) { return p != t_.p; }
86 int operator!=( T* p_ ) { return p != p_; }
87 friend int operator!=( T* p_, SmartPtr& t_ ) { return p_ != t_.p; }
90 void nullify() { if ( p ) p->downcount(); p = 0; }
92 bool isNull() const { return p == 0; }
95 T* p; // stored pointer
98 #define SMART( C ) SmartPtr<C>
100 template <class T1, class T2> SMART(T1) downcast( SMART(T2)& t )
102 return SMART(T1)(t.get());
105 #endif // __SUIT_SMARTPTR_H