X-Git-Url: http://git.tdb.fi/?a=blobdiff_plain;f=source%2Fcore%2Frefptr.h;h=dd07256d79d45ca1fa1ff558eacab32ca925ed79;hb=ae48dac6a368dbf68b1ec976254a5f896c5b737b;hp=ee020e0eb8783f3af6579f8960b4ae1707b9b18d;hpb=521cf1db00f8ce2d9f9494dca503d6c17d89ac2f;p=libs%2Fcore.git diff --git a/source/core/refptr.h b/source/core/refptr.h index ee020e0..dd07256 100644 --- a/source/core/refptr.h +++ b/source/core/refptr.h @@ -4,11 +4,16 @@ This file is part of libmspcore Copyright © 2006-2007 Mikko Rasa, Mikkosoft Productions Distributed under the LGPL */ + #ifndef MSP_CORE_REFPTR_H_ #define MSP_CORE_REFPTR_H_ 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 +21,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 +29,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 +52,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;