]> git.tdb.fi Git - libs/core.git/blobdiff - source/core/refptr.h
Win32 doesn't have execinfo.h, so don't include it
[libs/core.git] / source / core / refptr.h
index ee020e0eb8783f3af6579f8960b4ae1707b9b18d..a44c13c84e00da087d35f8a6a7776b2e1281c1e2 100644 (file)
@@ -9,6 +9,10 @@ Distributed under the LGPL
 
 namespace Msp {
 
 
 namespace Msp {
 
+/**
+A reference counting smart pointer.  When the last RefPtr for the data gets
+destroyed, the data is deleted as well.
+*/
 template<typename T>
 class RefPtr
 {
 template<typename T>
 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(): 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();
        RefPtr &operator=(const RefPtr &p)
        {
                decref();
@@ -26,6 +28,22 @@ public:
                incref();
                return *this;
        }
                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; }
 
        T *get() const        { return data; }
        T &operator*() const  { return *data; }
@@ -33,7 +51,7 @@ public:
        operator bool() const { return data!=0; }
 
        template<typename U>
        operator bool() const { return data!=0; }
 
        template<typename U>
-       static RefPtr<T> cast_dynamic(const RefPtr<U> &p)  { return RefPtr<T>(dynamic_cast<T *>(p.get()), p.count); }
+       static RefPtr<T> cast_dynamic(const RefPtr<U> &p)  { return RefPtr<T>(dynamic_cast<T *>(p.data), p.count); }
        template<typename U> friend class RefPtr;
 private:
        T        *data;
        template<typename U> friend class RefPtr;
 private:
        T        *data;