]> git.donarmstrong.com Git - lilypond.git/blob - flower/handle.hh
921dc6031c4a1d77e7f55dc15da3f3cdd89c894b
[lilypond.git] / flower / handle.hh
1 #ifndef HANDLE_HH
2 #define HANDLE_HH
3 /// reference counting handle
4 template<class T>
5 class Handle {
6     T *obj;
7     int *refs;
8
9     /// let go of ref. Delete if necessary
10     void down() {
11         if (!(*refs--)) {
12             delete obj;
13             delete refs;
14         }
15         obj = 0;
16         refs = 0;
17     }
18     /// point to new object. 
19     void up(T *t, int *r) {
20         if (!r) {
21             refs = new int;
22             *refs = 1;
23         } else {
24             refs =r;
25             *refs++;
26         }
27         obj = t;
28     }
29     /// POST: *refs == 1
30     void copy() {
31         if(*refs != 1){
32             T * newobj = new T(*obj );
33             down();
34             up(newobj);
35         }
36     }
37     Handle(Handle const &src) {
38         up(src.obj, src.refs);
39     }
40     Handle(T & o) {
41         up (&o);
42     }
43     void operator=(Handle const& src) {
44         if (this == &src)
45             return;
46         down();
47         up(src.o, src.refs);
48     }
49     operator const T&() {
50         return *obj;
51     }
52     operator T&() {
53         copy();
54         return *obj;
55     }
56 }
57 #endif