00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018 #ifndef SGWeakReferenced_HXX
00019 #define SGWeakReferenced_HXX
00020
00021 #include "SGReferenced.hxx"
00022 #include "SGSharedPtr.hxx"
00023
00024 template<typename T>
00025 class SGWeakPtr;
00026
00027 class SGWeakReferenced {
00028 public:
00037 SGWeakReferenced(void) :
00038 mWeakData(new WeakData(this))
00039 {}
00040 SGWeakReferenced(const SGWeakReferenced& weakReferenced) :
00041 mWeakData(new WeakData(this))
00042 {}
00043 ~SGWeakReferenced(void)
00044 { mWeakData->mWeakReferenced = 0; }
00045
00047 SGWeakReferenced& operator=(const SGWeakReferenced&)
00048 { return *this; }
00049
00052 static unsigned get(const SGWeakReferenced* ref)
00053 { if (ref) return ++(ref->mWeakData->mRefcount); else return 0u; }
00054 static unsigned put(const SGWeakReferenced* ref)
00055 { if (ref) return --(ref->mWeakData->mRefcount); else return ~0u; }
00056 static unsigned count(const SGWeakReferenced* ref)
00057 { if (ref) return ref->mWeakData->mRefcount; else return 0u; }
00058
00059 private:
00063 class WeakData : public SGReferenced {
00064 public:
00065 WeakData(SGWeakReferenced* weakReferenced) :
00066 mRefcount(0u),
00067 mWeakReferenced(weakReferenced)
00068 { }
00069
00070 template<typename T>
00071 T* getPointer()
00072 {
00073
00074
00075
00076
00077 unsigned count;
00078 do {
00079 count = mRefcount;
00080 if (count == 0)
00081 return 0;
00082 } while (!mRefcount.compareAndExchange(count, count + 1));
00083
00084
00085 return static_cast<T*>(mWeakReferenced);
00086 }
00087
00088 SGAtomic mRefcount;
00089 SGWeakReferenced* mWeakReferenced;
00090
00091 private:
00092 WeakData(void);
00093 WeakData(const WeakData&);
00094 WeakData& operator=(const WeakData&);
00095 };
00096
00097 SGSharedPtr<WeakData> mWeakData;
00098
00099 template<typename T>
00100 friend class SGWeakPtr;
00101 };
00102
00103 #endif