forked from kanaka/mal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RefCountedPtr.h
77 lines (58 loc) · 1.62 KB
/
RefCountedPtr.h
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#ifndef INCLUDE_REFCOUNTEDPTR_H
#define INCLUDE_REFCOUNTEDPTR_H
#include "Debug.h"
#include <cstddef>
class RefCounted {
public:
RefCounted() : m_refCount(0) { }
virtual ~RefCounted() { }
const RefCounted* acquire() const { m_refCount++; return this; }
int release() const { return --m_refCount; }
int refCount() const { return m_refCount; }
private:
RefCounted(const RefCounted&); // no copy ctor
RefCounted& operator = (const RefCounted&); // no assignments
mutable int m_refCount;
};
template<class T>
class RefCountedPtr {
public:
RefCountedPtr() : m_object(0) { }
RefCountedPtr(T* object) : m_object(0)
{ acquire(object); }
RefCountedPtr(const RefCountedPtr& rhs) : m_object(0)
{ acquire(rhs.m_object); }
const RefCountedPtr& operator = (const RefCountedPtr& rhs) {
acquire(rhs.m_object);
return *this;
}
bool operator == (const RefCountedPtr& rhs) const {
return m_object == rhs.m_object;
}
bool operator != (const RefCountedPtr& rhs) const {
return m_object != rhs.m_object;
}
operator bool () const {
return m_object != NULL;
}
~RefCountedPtr() {
release();
}
T* operator -> () const { return m_object; }
T* ptr() const { return m_object; }
private:
void acquire(T* object) {
if (object != NULL) {
object->acquire();
}
release();
m_object = object;
}
void release() {
if ((m_object != NULL) && (m_object->release() == 0)) {
delete m_object;
}
}
T* m_object;
};
#endif // INCLUDE_REFCOUNTEDPTR_H