blob: 1b5d2bc197add850aa54d13bad15e5012af1e2f6 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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_*/
|