1 #ifndef MSP_CORE_REFPTR_H_
2 #define MSP_CORE_REFPTR_H_
7 A reference counting smart pointer. When the last RefPtr for the data gets
8 destroyed, the data is deleted as well.
13 template<typename U> friend class RefPtr;
18 KEEP = 1U<<(sizeof(unsigned)*8-1)
25 RefPtr(): data(0), count(0) { }
26 RefPtr(T *d): data(d), count(data ? new unsigned(1) : 0) { }
28 RefPtr(T *d, unsigned *c): data(d), count(d ? c : 0) { incref(); }
31 /* Must have this or the compiler will generate a default copy-c'tor despite
32 the template version */
33 RefPtr(const RefPtr &p): data(p.data), count(p.count) { incref(); }
36 RefPtr(const RefPtr<U> &p): data(p.data), count(p.count) { incref(); }
38 ~RefPtr() { decref(); }
40 RefPtr &operator=(T *d)
44 count = (d ? new unsigned(1) : 0);
48 // Likewise for the assignment operator
49 RefPtr &operator=(const RefPtr &p) { return assign(p); }
52 RefPtr &operator=(const RefPtr<U> &p) { return assign(p); }
56 RefPtr &assign(const RefPtr<U> &p)
66 /** Makes the RefPtr release its reference of the data without deleting it.
67 Note that if there are other RefPtrs left with the same data, it might
68 still get deleted automatically. */
78 /** Marks the data to not be deleted. This affects all RefPtrs with the
86 T *get() const { return data; }
87 T &operator*() const { return *data; }
88 T *operator->() const { return data; }
89 operator bool() const { return data!=0; }
92 static RefPtr<T> cast_dynamic(const RefPtr<U> &p)
93 { return RefPtr<T>(dynamic_cast<T *>(p.data), p.count); }
113 else if(*count==KEEP)