SafePtr.h
Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010 #ifndef SAFE_PTR_H
00011 #define SAFE_PTR_H
00012
00013 #include "Slot.h"
00014 #include "Subject.h"
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033 template<typename T>
00034 class SafePtr
00035 {
00036 public:
00037
00038
00039
00040
00041
00042 SafePtr() : mpSubject(NULL)
00043 {
00044 }
00045
00046
00047
00048
00049
00050
00051
00052 SafePtr(T* pSubject) :
00053 mpSubject(pSubject)
00054 {
00055 attachToDeleted();
00056 }
00057
00058
00059
00060
00061
00062
00063 virtual ~SafePtr()
00064 {
00065 detachFromDeleted();
00066 mpSubject = NULL;
00067 }
00068
00069
00070
00071
00072
00073
00074
00075
00076
00077
00078 void reset(T* pSubject = NULL)
00079 {
00080 if (pSubject != mpSubject)
00081 {
00082 detachFromDeleted();
00083 mpSubject = pSubject;
00084 attachToDeleted();
00085 }
00086 }
00087
00088
00089
00090
00091
00092
00093 T* get()
00094 {
00095 return mpSubject;
00096 }
00097
00098
00099
00100
00101 const T* get() const
00102 {
00103 return mpSubject;
00104 }
00105
00106
00107
00108
00109 T* operator->()
00110 {
00111 return get();
00112 }
00113
00114
00115
00116
00117 const T* operator->() const
00118 {
00119 return get();
00120 }
00121
00122 protected:
00123
00124
00125
00126
00127
00128
00129
00130
00131
00132
00133 void attach(const std::string& signal, const Slot& slot)
00134 {
00135 if (mpSubject != NULL)
00136 {
00137 mpSubject->attach(signal, slot);
00138 }
00139 }
00140
00141
00142
00143
00144
00145
00146
00147
00148
00149
00150
00151 void detach(const std::string& signal, const Slot& slot)
00152 {
00153 if (mpSubject != NULL)
00154 {
00155 mpSubject->detach(signal, slot);
00156 }
00157 }
00158
00159 private:
00160 SafePtr(const SafePtr&);
00161 SafePtr& operator=(const SafePtr&);
00162
00163 void attachToDeleted()
00164 {
00165 attach(SIGNAL_NAME(Subject, Deleted), Slot(this, &SafePtr::subjectDeleted));
00166 }
00167
00168 void detachFromDeleted()
00169 {
00170 detach(SIGNAL_NAME(Subject, Deleted), Slot(this, &SafePtr::subjectDeleted));
00171 }
00172
00173 void subjectDeleted(Subject& subject, const std::string& signal, const boost::any& data)
00174 {
00175 if (&subject == mpSubject)
00176 {
00177 mpSubject = NULL;
00178 }
00179 }
00180
00181 T* mpSubject;
00182 };
00183
00184 #endif