3 This file is part of libmspcore
4 Copyright © 2006-2007, 2010-2011 Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
8 #ifndef MSP_CORE_REFPTR_H_
9 #define MSP_CORE_REFPTR_H_
14 A reference counting smart pointer. When the last RefPtr for the data gets
15 destroyed, the data is deleted as well.
20 template<typename U> friend class RefPtr;
25 KEEP = 1U<<(sizeof(unsigned)*8-1)
32 RefPtr(): data(0), count(0) { }
33 RefPtr(T *d): data(d), count(data ? new unsigned(1) : 0) { }
35 RefPtr(T *d, unsigned *c): data(d), count(d ? c : 0) { incref(); }
38 /* Must have this or the compiler will generate a default copy-c'tor despite
39 the template version */
40 RefPtr(const RefPtr &p): data(p.data), count(p.count) { incref(); }
43 RefPtr(const RefPtr<U> &p): data(p.data), count(p.count) { incref(); }
45 ~RefPtr() { decref(); }
47 RefPtr &operator=(T *d)
51 count = (d ? new unsigned(1) : 0);
55 // Likewise for the assignment operator
56 RefPtr &operator=(const RefPtr &p) { return assign(p); }
59 RefPtr &operator=(const RefPtr<U> &p) { return assign(p); }
63 RefPtr &assign(const RefPtr<U> &p)
73 /** Makes the RefPtr release its reference of the data without deleting it.
74 Note that if there are other RefPtrs left with the same data, it might
75 still get deleted automatically. */
85 /** Marks the data to not be deleted. This affects all RefPtrs with the
93 T *get() const { return data; }
94 T &operator*() const { return *data; }
95 T *operator->() const { return data; }
96 operator bool() const { return data!=0; }
99 static RefPtr<T> cast_dynamic(const RefPtr<U> &p)
100 { return RefPtr<T>(dynamic_cast<T *>(p.data), p.count); }
120 else if(*count==KEEP)