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