COOPY » Guide  version 0.6.5
/home/paulfitz/cvs/coopy_scm/coopy/src/libcoopy_core/include/coopy/RefCount.h
Go to the documentation of this file.
00001 #ifndef COOPY_REFCOUNT
00002 #define COOPY_REFCOUNT
00003 
00004 #include <coopy/Dbg.h>
00005 
00006 namespace coopy {
00007   namespace store {
00008     class RefCount;
00009     template <class T> class Poly;
00010   }
00011 }
00012 
00019 class coopy::store::RefCount {
00020 private:
00021   int ref_ct;
00022 public:
00023   RefCount() {
00024     ref_ct = 0;
00025   }
00026 
00027   virtual ~RefCount() {
00028   }
00029 
00030   int addReference() {
00031     ref_ct++;
00032     return ref_ct;
00033   }
00034 
00035   int removeReference() {
00036     ref_ct--;
00037     return ref_ct;
00038   }
00039 
00040   int getReferenceCount() {
00041     return ref_ct;
00042   }
00043 };
00044 
00045 template <class T>
00046 class coopy::store::Poly {
00047 private:
00048   T *ref;
00049   bool owned;
00050 public:
00051   Poly() {
00052     ref = 0/*NULL*/;
00053     owned = false;
00054   }
00055 
00056   Poly(T *ref, bool owned) : ref(ref), owned(owned) {
00057     if (ref!=0/*NULL*/&&owned) {
00058       ref->addReference();
00059     }
00060   }
00061 
00062   Poly(const Poly& alt) {
00063     owned = alt.owned;
00064     ref = alt.ref;
00065     if (ref!=0/*NULL*/&&owned) {
00066       ref->addReference();
00067     }
00068   }
00069 
00070   const Poly& operator = (const Poly& alt) {
00071     clear();
00072     owned = alt.owned;
00073     ref = alt.ref;
00074     if (ref!=0/*NULL*/&&owned) {
00075       ref->addReference();
00076     }
00077     return *this;
00078   }
00079 
00080   virtual ~Poly() {
00081     clear();
00082   }
00083 
00084   void clear() {
00085     if (ref==0/*NULL*/) return;
00086     if (owned) {
00087       int ct = ref->removeReference();
00088       if (ct==0) {
00089         delete ref;
00090       }
00091     }
00092     ref = 0/*NULL*/;
00093   }
00094 
00095   bool isValid() const {
00096     return ref!=0/*NULL*/;
00097   }
00098 
00099   T& operator *() const {
00100     COOPY_ASSERT(ref!=0);
00101     return *ref;
00102   }
00103 
00104   T *operator ->() const {
00105     COOPY_ASSERT(ref!=0);
00106     return ref;
00107   }
00108 
00109   T *getContent() const {
00110     return ref;
00111   }
00112 
00113 
00114 };
00115 
00116 #endif
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Defines