X-Git-Url: http://git.tdb.fi/?p=libs%2Fcore.git;a=blobdiff_plain;f=source%2Fcore%2Frefptr.h;h=a44c13c84e00da087d35f8a6a7776b2e1281c1e2;hp=ee020e0eb8783f3af6579f8960b4ae1707b9b18d;hb=d61b4678e4e4a2a3661a2472dc7349cc9fd5eaad;hpb=9e8e96c9e98e4aed3713ca09011aebafc9f62f87 diff --git a/source/core/refptr.h b/source/core/refptr.h index ee020e0..a44c13c 100644 --- a/source/core/refptr.h +++ b/source/core/refptr.h @@ -9,6 +9,10 @@ Distributed under the LGPL namespace Msp { +/** +A reference counting smart pointer. When the last RefPtr for the data gets +destroyed, the data is deleted as well. +*/ template class RefPtr { @@ -16,8 +20,6 @@ public: RefPtr(): data(0), count(0) { } RefPtr(T *d): data(d), count(0) { if(data) count=new unsigned(1); } RefPtr(const RefPtr &p): data(p.data), count(p.count) { incref(); } - ~RefPtr() { decref(); } - RefPtr &operator=(const RefPtr &p) { decref(); @@ -26,6 +28,22 @@ public: incref(); return *this; } + + ~RefPtr() { decref(); } + + /** + Makes the RefPtr release its reference of the data. Note that if there are + other RefPtrs left with the same data, it might still get deleted + automatically. + */ + T *release() + { + T *d=data; + data=0; + decref(); + count=0; + return d; + } T *get() const { return data; } T &operator*() const { return *data; } @@ -33,7 +51,7 @@ public: operator bool() const { return data!=0; } template - static RefPtr cast_dynamic(const RefPtr &p) { return RefPtr(dynamic_cast(p.get()), p.count); } + static RefPtr cast_dynamic(const RefPtr &p) { return RefPtr(dynamic_cast(p.data), p.count); } template friend class RefPtr; private: T *data;