00001 #ifndef COUNT_PTR_H_
00002 #define COUNT_PTR_H_
00003
00004 #include <algorithm>
00005
00006
00007
00008 template <class T>
00009 class count_ptr {
00010 private:
00011 T* m_ptr;
00012 long *m_count;
00013 public:
00014
00015 explicit count_ptr(T* ptr = 0)
00016 : m_ptr(ptr), m_count(new long(1))
00017 { }
00018 count_ptr(const count_ptr<T> &p)
00019 : m_ptr(p.m_ptr), m_count(p.m_count)
00020 {
00021 ++*m_count;
00022 }
00023 ~count_ptr() throw ()
00024 {
00025 cancel();
00026 }
00027
00028 count_ptr<T>& operator=(count_ptr<T> temp)
00029 {
00030 swap(temp);
00031 return *this;
00032 }
00033
00034
00035 T& operator*() const
00036 {
00037 return *m_ptr;
00038 }
00039 T* operator->() const throw()
00040 {
00041 return m_ptr;
00042 }
00043 int equiv(const count_ptr<T>& p) const throw()
00044 {
00045 return m_ptr == p.m_ptr;
00046 }
00047 T* get_ptr() const throw()
00048 {
00049 return m_ptr;
00050 }
00051 long count() const
00052 {
00053 return *m_count;
00054 }
00055 void swap (count_ptr<T> &a) throw()
00056 {
00057 std::swap(m_ptr,a.m_ptr);
00058 std::swap(m_count,a.m_count);
00059 }
00060 int compare (const count_ptr<T> &a) const
00061 {
00062 if (m_ptr < a.m_ptr)
00063 return -1;
00064 else if (m_ptr > a.m_ptr)
00065 return 1;
00066 return 0;
00067 }
00068 private:
00069 void cancel ()
00070 {
00071 if (0 == --*m_count)
00072 {
00073 delete m_count;
00074 delete m_ptr;
00075 }
00076 }
00077 };
00078
00079 template <class T>
00080 inline void swap (count_ptr<T> &a, count_ptr<T> &b)
00081 {
00082 a.swap(b);
00083 }
00084
00085 template <class T>
00086 inline bool operator< (const count_ptr<T> &a, const count_ptr<T> &b)
00087 {
00088 return a.compare(b) < 0;
00089 }
00090 template <class T>
00091 inline bool operator> (const count_ptr<T> &a, const count_ptr<T> &b)
00092 {
00093 return a.compare(b) > 0;
00094 }
00095 template <class T>
00096 inline bool operator<= (const count_ptr<T> &a, const count_ptr<T> &b)
00097 {
00098 return a.compare(b) <= 0;
00099 }
00100 template <class T>
00101 inline bool operator>= (const count_ptr<T> &a, const count_ptr<T> &b)
00102 {
00103 return a.compare(b) >= 0;
00104 }
00105 template <class T>
00106 inline bool operator== (const count_ptr<T> &a, const count_ptr<T> &b)
00107 {
00108 return a.compare(b) == 0;
00109 }
00110 template <class T>
00111 inline bool operator!= (const count_ptr<T> &a, const count_ptr<T> &b)
00112 {
00113 return !(a == b);
00114 }
00115
00116 #endif