initial
[prop.git] / include / AD / generic / ref.h
blobb7ea763efc8d824faf94d1045fda9a01910a8337
1 //////////////////////////////////////////////////////////////////////////////
2 // NOTICE:
3 //
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
9 // your programs.
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
16 // code.
18 // This software is still under development and we welcome any suggestions
19 // and help from the users.
21 // Allen Leung
22 // 1994
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.
39 template<class Type>
40 class Ref {
41 Type * object; // The object itself
42 int * refCount; // number of Ref's in existence
43 public:
44 Ref(const Ref & r) : object(r.object), refCount(r.refCount)
45 { ++*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);
55 template<class Type>
56 Ref<Type>& Ref<Type>::operator = (const Ref<Type>& r)
57 { if (this != &r) {
58 if (--*refCount == 0) { delete object; delete refCount; }
59 object = r.object; refCount = r.refCount; ++*refCount;
61 return *this;
64 #endif