3 This file is part of libmspcore
4 Copyright © 2006-2007, 2010 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.
23 KEEP = 1U<<(sizeof(unsigned)*8-1)
27 RefPtr(): data(0), count(0) { }
28 RefPtr(T *d): data(d), count(data ? new unsigned(1) : 0) { }
30 // Must have this or the compiler will generate a default copy-c'tor
31 RefPtr(const RefPtr &p): data(p.data), count(p.count) { incref(); }
34 RefPtr(const RefPtr<U> &p): data(p.data), count(p.count) { incref(); }
36 RefPtr &operator=(T *d)
40 count = (d ? new unsigned(1) : 0);
44 // Likewise for the assignment operator
45 RefPtr &operator=(const RefPtr &p) { return assign(p); }
48 RefPtr &operator=(const RefPtr<U> &p) { return assign(p); }
50 ~RefPtr() { decref(); }
53 Makes the RefPtr release its reference of the data. Note that if there are
54 other RefPtrs left with the same data, it might still get deleted
67 Marks the data to not be deleted. This affects all RefPtrs with the same
76 T *get() const { return data; }
77 T &operator*() const { return *data; }
78 T *operator->() const { return data; }
79 operator bool() const { return data!=0; }
82 static RefPtr<T> cast_dynamic(const RefPtr<U> &p)
83 { return RefPtr<T>(dynamic_cast<T *>(p.data), p.count); }
85 template<typename U> friend class RefPtr;
90 RefPtr(T *d, unsigned *c): data(d), count(d ? c : 0) { incref(); }
93 RefPtr &assign(const RefPtr<U> &p)
119 else if(*count==KEEP)