1 //////////////////////////////////////////////////////////////////////////////
4 // ADLib, Prop and their related set of tools and documentation are in the
5 // public domain. The author(s) of this software reserve no copyrights on
6 // the source code and any code generated using the tools. You are encouraged
7 // to use ADLib and Prop to develop software, in both academic and commercial
8 // settings, and are free to incorporate any part of ADLib and Prop into
11 // Although you are under no obligation to do so, we strongly recommend that
12 // you give away all software developed using our tools.
14 // We also ask that credit be given to us when ADLib and/or Prop are used in
15 // your programs, and that this notice be preserved intact in all the source
18 // This software is still under development and we welcome any suggestions
19 // and help from the users.
23 //////////////////////////////////////////////////////////////////////////////
25 #ifndef reference_counting_pointer_h
26 #define reference_counting_pointer_h
29 // Class Ref<Type> takes a pointer to an object and
30 // performs transparent reference counting on it.
31 // Assignment and initialization will change its reference.
32 // When the reference count of the object reaches 0, it
33 // will be automatically deleted.
35 // Warning: circular objects built from this type will be not
36 // be reference counted correctly and space leak will result.
41 Type
* object
; // The object itself
42 int * refCount
; // number of Ref's in existence
44 Ref(const Ref
& r
) : object(r
.object
), refCount(r
.refCount
)
46 Ref(Type
* obj
) : object(obj
), refCount(new int) {}
47 ~Ref() { if (--(*refCount
) == 0) { delete object
; delete refCount
; }}
49 Type
* operator -> () { return object
; }
50 Type
* operator * () { return object
; }
52 Ref
& operator = (const Ref
& r
);
56 Ref
<Type
>& Ref
<Type
>::operator = (const Ref
<Type
>& r
)
58 if (--*refCount
== 0) { delete object
; delete refCount
; }
59 object
= r
.object
; refCount
= r
.refCount
; ++*refCount
;