00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020 #ifndef NEWNET_WEAKREFPTR_H
00021 #define NEWNET_WEAKREFPTR_H
00022
00023 #include "nnbaseptr.h"
00024 #include "nnguardobject.h"
00025
00026 namespace NewNet
00027 {
00028 class Object;
00029
00031
00035 template<class T> class WeakRefPtr : public BasePtr<T>
00036 {
00037 private:
00038 #ifndef DOXYGEN_UNDOCUMENTED
00039 class GuardObjectCallback : public GuardObject::Callback
00040 {
00041 public:
00042 GuardObjectCallback(WeakRefPtr * ptr) : m_Ptr(ptr)
00043 {
00044 }
00045
00046 void operator()(Object * p)
00047 {
00048 m_Ptr->objectDestroyed(p);
00049 }
00050
00051 private:
00052 WeakRefPtr * m_Ptr;
00053 };
00054
00055 GuardObjectCallback * m_GuardObjectCallback;
00056 #endif // DOXYGEN_UNDOCUMENTED
00057
00058 public:
00060
00061 WeakRefPtr() : BasePtr<T>()
00062 {
00063 m_GuardObjectCallback = new GuardObjectCallback(this);
00064 }
00065
00067
00068 WeakRefPtr(T * t) : BasePtr<T>(t)
00069 {
00070 m_GuardObjectCallback = new GuardObjectCallback(this);
00071 if(t)
00072 t->guardObject() += m_GuardObjectCallback;
00073 }
00074
00076
00077 WeakRefPtr(const WeakRefPtr& t) : BasePtr<T>(t.m_Ptr)
00078 {
00079 m_GuardObjectCallback = new GuardObjectCallback(this);
00080 if(t.m_Ptr)
00081 t.m_Ptr->guardObject() += m_GuardObjectCallback;
00082 }
00083
00085
00086 WeakRefPtr& operator=(const WeakRefPtr& t)
00087 {
00088 if(BasePtr<T>::m_Ptr == t.m_Ptr)
00089 return *this;
00090 if(BasePtr<T>::m_Ptr)
00091 BasePtr<T>::m_Ptr->guardObject() -= m_GuardObjectCallback;
00092 BasePtr<T>::m_Ptr = t.m_Ptr;
00093 if(t.m_Ptr)
00094 BasePtr<T>::m_Ptr->guardObject() += m_GuardObjectCallback;
00095 return *this;
00096 }
00097
00099
00100 WeakRefPtr& operator=(T * t)
00101 {
00102 if(BasePtr<T>::m_Ptr == t)
00103 return *this;
00104 if(BasePtr<T>::m_Ptr)
00105 BasePtr<T>::m_Ptr->guardObject() -= m_GuardObjectCallback;
00106 BasePtr<T>::m_Ptr = t;
00107 if(t)
00108 t->guardObject() += m_GuardObjectCallback;
00109 return *this;
00110 }
00111
00112 #ifndef DOXYGEN_UNDOCUMENTED
00113 ~WeakRefPtr()
00114 {
00115 if(BasePtr<T>::m_Ptr)
00116 BasePtr<T>::m_Ptr->guardObject() -= m_GuardObjectCallback;
00117 delete m_GuardObjectCallback;
00118 }
00119 #endif // DOXYGEN_UNDOCUMENTED
00120
00121 protected:
00122 #ifndef DOXYGEN_UNDOCUMENTED
00123 void objectDestroyed(Object * p)
00124 {
00125 #ifdef NN_PTR_DEBUG
00126 assert(p == BasePtr<T>::m_Ptr);
00127 #endif
00128 BasePtr<T>::m_Ptr = 0;
00129 }
00130 #endif // DOXYGEN_UNDOCUMENTED
00131 };
00132 }
00133
00134 #undef NN_PTR_CHECK
00135
00136 #endif // NEWNET_REFPTR_H