blob: 32573998f270c8916ffe1257bfe677ef466875bd (
about) (
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
47
48
49
50
51
52
53
54
55
56
57
|
#ifndef HANDLE_HH
#define HANDLE_HH
/// reference counting handle
template<class T>
class Handle {
T *obj;
int *refs;
/// let go of ref. Delete if necessary
void down() {
if (!(*refs--)) {
delete obj;
delete refs;
}
obj = 0;
refs = 0;
}
/// point to new object.
void up(T *t, int *r=0) {
if (!r) {
refs = new int;
*refs = 1;
} else {
refs =r;
*refs++;
}
obj = t;
}
/// POST: *refs == 1
void copy() {
if(*refs != 1){
T * newobj = new T(*obj );
down();
up(newobj);
}
}
Handle(Handle const &src) {
up(src.obj, src.refs);
}
Handle(T & o) {
up (&o);
}
void operator=(Handle const& src) {
if (this == &src)
return;
down();
up(src.o, src.refs);
}
operator const T&() {
return *obj;
}
operator T&() {
copy();
return *obj;
}
}
#endif
|