00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00029 #ifndef OW32_smart_ptr_h
00030 #define OW32_smart_ptr_h
00031
00032 namespace OW32
00033 {
00034
00037 class smart_ptr_single_thread_model
00038 {
00039 public:
00040 static LONG increment(LPLONG p) { return ++(*p); }
00041 static LONG decrement(LPLONG p) { return --(*p); }
00042 };
00043
00046 class smart_ptr_multi_thread_model
00047 {
00048 public:
00049 static LONG increment(LPLONG p) { return InterlockedIncrement(p); }
00050 static LONG decrement(LPLONG p) { return InterlockedDecrement(p); }
00051 };
00052
00056 template <class T, class thread_model = smart_ptr_multi_thread_model>
00057 class smart_ptr
00058 {
00059 T* m_ptr;
00060 LONG* m_count;
00061
00062 public:
00063 smart_ptr() : m_ptr(0),m_count(0L) {}
00064 explicit smart_ptr(T* ptr) : m_ptr(ptr),m_count(new LONG(1L)) {}
00065
00066 smart_ptr(const smart_ptr<T>& other) :
00067 m_ptr(other.m_ptr),
00068 m_count(other.m_count)
00069 {
00070 if (m_count) thread_model::increment(m_count);
00071 }
00072
00073 smart_ptr& operator=(const smart_ptr& other)
00074 {
00075 if (this != &other)
00076 {
00077 release();
00078 m_ptr = other.m_ptr;
00079 m_count = other.m_count;
00080 if (m_count) thread_model::increment(m_count);
00081 }
00082 return *this;
00083 }
00084
00085 ~smart_ptr() { release(); }
00086
00087 void release() {
00088 if (m_count && thread_model::decrement(m_count)==0) {
00089 delete m_ptr;
00090 delete m_count;
00091 }
00092 m_ptr = 0;
00093 m_count = 0;
00094 }
00095
00096 T* get() {
00097 return m_ptr;
00098 }
00099
00100 void reset(T* newptr) {
00101 release();
00102 m_ptr = T;
00103 m_count = new LONG(1L);
00104 }
00105
00106 operator T*() const { return m_ptr; }
00107 T* operator->() const { return m_ptr; }
00108 };
00109
00110 }
00111
00112 #endif // OW32_smart_ptr_h