00001
00002
00003
00004
00005
00006 #ifndef REFCOUNT_H
00007 #define REFCOUNT_H
00008
00009 #include<iostream>
00010
00013 template<typename T>
00014 class RefCount
00015 {
00016 public:
00018 RefCount(T s) {
00019 impl = new T(s);
00020 count = new unsigned int(1);
00021 }
00022
00024 RefCount(T *s = 0) {
00025 impl = s;
00026 count = new unsigned int(1);
00027 }
00028
00030 RefCount(const RefCount &s) : impl(s.impl), count(s.count) {
00031 ++(*count);
00032 }
00033
00038 ~RefCount() {
00039 if (--(*count) == 0) {
00040 delete impl;
00041 delete count;
00042 }
00043 }
00044
00046 RefCount copy() {
00047 RefCount tmp(*impl);
00048 return tmp;
00049 }
00051 void swap(RefCount &s) {
00052 unsigned int *tCount = count;
00053 count = s.count;
00054 s.count = tCount;
00055 T *tImpl = impl;
00056 impl = s.impl;
00057 s.impl = tImpl;
00058 }
00059
00062 RefCount &operator=(const RefCount &s) {
00063 RefCount tmp(s);
00064 swap(tmp);
00065 return *this;
00066 }
00067
00070 template<typename S>
00071 RefCount &operator=(const RefCount<S> &s) {
00072 RefCount tmp(static_cast<T*>(s.data()), s.getCount());
00073 swap(tmp);
00074 return *this;
00075 }
00076
00080 RefCount &operator=(T *s) {
00081 if (--(*count) == 0) {
00082 delete impl;
00083 }
00084 *count = 1;
00085 impl = s;
00086 return *this;
00087 }
00088
00090 T *operator->() { return impl; }
00091
00095 T *data() const { return impl; }
00096
00100 unsigned int *getCount() const {
00101 return count;
00102 }
00103
00104 private:
00106 RefCount(T *t, unsigned int *c) : impl(t), count(c) {
00107 if (t != 0) {
00108 ++(*count);
00109 } else {
00110 count = new unsigned int(1);
00111 }
00112 }
00113
00115 T *impl;
00116
00118 unsigned int *count;
00119 };
00120
00121 #endif