00001
00002
00003
00004
00005
00006 #ifndef __REFCOUNT_H__
00007 #define __REFCOUNT_H__
00008
00009 #include <windows.h>
00010
00011
00012 class RefCountObj
00013 {
00014 public:
00015
00016 RefCountObj() : _ref_count (0) {}
00017 RefCountObj(const RefCountObj &) : _ref_count (0) {}
00018 virtual ~RefCountObj() {}
00019
00020
00021 RefCountObj& operator = (const RefCountObj &)
00022 {
00023 return *this;
00024 }
00025
00026 void add_ref() const
00027 {
00028 ++_ref_count;
00029 }
00030
00031 void remove_ref() const
00032 {
00033 if (--_ref_count == 0)
00034 delete this;
00035 }
00036
00037 private:
00038 mutable unsigned int _ref_count;
00039 };
00040
00041
00042
00043 template <class T>
00044 class RefCountPtr
00045 {
00046 public:
00047
00048 RefCountPtr(T* real_ptr = 0);
00049 RefCountPtr(const RefCountPtr<T> &rhs);
00050 ~RefCountPtr();
00051
00052
00053 RefCountPtr<T> & operator = (const RefCountPtr<T> &rhs);
00054
00055 T* operator -> ();
00056 T& operator * ();
00057 const T* operator -> () const;
00058 const T& operator * () const;
00059
00060 operator bool () const;
00061
00062 private:
00063 T* _ptr;
00064 };
00065
00066 template <class T>
00067 RefCountPtr<T>::RefCountPtr(T* real_ptr) :
00068 _ptr (real_ptr)
00069 {
00070 if (_ptr != NULL)
00071 _ptr->add_ref();
00072 }
00073
00074 template <class T>
00075 RefCountPtr<T>::RefCountPtr(const RefCountPtr<T> &rhs) :
00076 _ptr (rhs._ptr)
00077 {
00078 if (_ptr != NULL)
00079 _ptr->add_ref();
00080 }
00081
00082 template <class T>
00083 RefCountPtr<T>::~RefCountPtr()
00084 {
00085 if (_ptr != NULL)
00086 _ptr->remove_ref();
00087 }
00088
00089 template <class T>
00090 RefCountPtr<T>& RefCountPtr<T>::operator = (const RefCountPtr<T> &rhs)
00091 {
00092 if (_ptr != rhs._ptr)
00093 {
00094 if (_ptr != NULL)
00095 _ptr->remove_ref();
00096
00097 _ptr = rhs._ptr;
00098
00099 if (_ptr != NULL)
00100 _ptr->add_ref();
00101 }
00102 return *this;
00103 }
00104
00105 template <class T>
00106 const T* RefCountPtr<T>::operator -> () const
00107 {
00108 return _ptr;
00109 }
00110
00111 template <class T>
00112 T* RefCountPtr<T>::operator -> ()
00113 {
00114 return _ptr;
00115 }
00116
00117 template <class T>
00118 const T& RefCountPtr<T>::operator * () const
00119 {
00120 return *_ptr;
00121 }
00122
00123 template <class T>
00124 T& RefCountPtr<T>::operator * ()
00125 {
00126 return *_ptr;
00127 }
00128
00129 template <class T>
00130 RefCountPtr<T>::operator bool () const
00131 {
00132 return (_ptr != NULL);
00133 }
00134
00135 #endif // __REFCOUNT_H__