-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathsimple_shared_ptr.h
More file actions
58 lines (56 loc) · 1 KB
/
simple_shared_ptr.h
File metadata and controls
58 lines (56 loc) · 1 KB
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
#ifndef SIMPLE_SHARED_PTR_H
#define SIMPLE_SHARED_PTR_H
template <class E>
class simple_shared_ptr {
public:
simple_shared_ptr() : refcnt(NULL), ptr(NULL) {}
simple_shared_ptr(E *p) : refcnt(NULL), ptr(NULL) {
ref(p);
}
simple_shared_ptr(const simple_shared_ptr &rhs) : refcnt(NULL), ptr(NULL) {
(*this) = rhs;
}
simple_shared_ptr<E> &operator=(const simple_shared_ptr &rhs) {
if (refcnt != rhs.refcnt) {
unref();
refcnt = rhs.refcnt;
if (refcnt) (*refcnt)++;
ptr = rhs.ptr;
}
return *this;
}
void reset(E *p) {
unref();
ref(p);
}
E *get() {
return ptr;
}
E *operator->() {
return ptr;
}
E &operator*() {
return *ptr;
}
~simple_shared_ptr() {
unref();
}
private:
int *refcnt;
E *ptr;
void ref(E *p) {
refcnt = new int(1);
ptr = p;
}
void unref() {
if (refcnt) {
if (--(*refcnt) == 0) {
delete refcnt;
delete ptr;
}
refcnt = NULL;
ptr = NULL;
}
}
};
#endif