summaryrefslogtreecommitdiffstats
path: root/SharedPtr.h
diff options
context:
space:
mode:
Diffstat (limited to 'SharedPtr.h')
-rw-r--r--SharedPtr.h46
1 files changed, 46 insertions, 0 deletions
diff --git a/SharedPtr.h b/SharedPtr.h
new file mode 100644
index 0000000..1b5d2bc
--- /dev/null
+++ b/SharedPtr.h
@@ -0,0 +1,46 @@
+#ifndef SHAREDPTR_H_
+#define SHAREDPTR_H_
+
+template <class T>
+class SharedPtr {
+ private:
+ class Counter {
+ public:
+ Counter(T *o) : object(o), refCount(1) {}
+ ~Counter() {delete object;}
+
+ T *object;
+ unsigned int refCount;
+ };
+
+ Counter *counter;
+
+ public:
+ SharedPtr(T *o) : counter(new Counter(o)) {}
+
+ SharedPtr(const SharedPtr<T> &c) : counter(c.counter) {
+ counter->refCount++;
+ }
+
+ virtual ~SharedPtr() {
+ if(--counter->refCount == 0)
+ delete counter;
+ }
+
+ SharedPtr<T>& operator=(const SharedPtr<T>& c) {
+ c.counter->refCount++;
+ if(--counter->refCount == 0)
+ delete counter;
+
+ counter = c.counter;
+ return *this;
+ }
+
+ T* operator->() {return counter->object;}
+ T& operator*() {return *counter->object;}
+
+ const T* operator->() const {return counter->object;}
+ const T& operator*() const {return *counter->object;}
+};
+
+#endif /*SHAREDPTR_H_*/