00001 #ifndef MISC_REFCOUNT_H
00002 #define MISC_REFCOUNT_H
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00033 #include <glt/config.h>
00034
00035 #include <cassert>
00036
00057 template<class T>
00058 class ReferenceCountPtr
00059 {
00060 public:
00061
00063 ReferenceCountPtr()
00064 : _obj(NULL), _count(NULL)
00065 {
00066 }
00067
00069 ReferenceCountPtr(T *obj)
00070 : _obj(obj), _count(new int)
00071 {
00072 *_count = 0;
00073 inc();
00074 }
00075
00077 ReferenceCountPtr(const ReferenceCountPtr &ptr)
00078 : _obj(ptr._obj), _count(ptr._count)
00079 {
00080 inc();
00081 }
00082
00084 ~ReferenceCountPtr()
00085 {
00086 dec();
00087 }
00088
00090 ReferenceCountPtr &operator=(const ReferenceCountPtr &ptr)
00091 {
00092 dec();
00093
00094 _count = ptr._count;
00095 _obj = ptr._obj;
00096
00097 inc();
00098
00099 return *this;
00100 }
00101
00103 void clear() { dec(); }
00105 void reset() { dec(); }
00106
00108 inline T &operator*() { assert(_obj); return *_obj; }
00110 inline T *operator->() { assert(_obj); return _obj; }
00112 inline T *get() { return _obj; }
00113
00115 inline const T &operator*() const { assert(_obj); return *_obj; }
00117 inline const T *operator->() const { assert(_obj); return _obj; }
00119 inline const T *get() const { return _obj; }
00120
00121 private:
00122 T *_obj;
00123 int *_count;
00124
00125 void inc()
00126 {
00127 if (_count)
00128 (*_count)++;
00129 }
00130
00131 void dec()
00132 {
00133 if (_count)
00134 {
00135 (*_count)--;
00136 if (*_count==0)
00137 {
00138 delete _obj;
00139 delete _count;
00140 }
00141 }
00142
00143 _obj = NULL;
00144 _count = NULL;
00145 }
00146 };
00147
00148 #endif