-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcountptr.h
More file actions
48 lines (40 loc) · 753 Bytes
/
countptr.h
File metadata and controls
48 lines (40 loc) · 753 Bytes
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
#ifndef COUNTEDPTR_H
#define COUNTEDPTR_H
template<typename T>
class CountedPtr {
private :
T* ptr;
long *count;
public :
explicit CountedPtr(T *p = 0) : ptr(p), count(new long(1)) { }
CountedPtr(const CountedPtr<T>& p) throw()
: ptr(p.ptr), count(p.count) {
++*count;
}
~CountedPtr() throw () {
dispose();
}
CountedPtr<T>& operator = (const CountedPtr<T>& p) throw () {
if (this != &p) {
dispose();
ptr = p.ptr;
count = p.count;
++*count;
}
return *this;
}
T& operator*() const throw () {
return *ptr;
}
T* operator->() const throw () {
return ptr;
}
private :
void dispose() {
if (--count == 0) {
delete count;
delete ptr;
}
}
};
#endif