Procházet zdrojové kódy

Introduce convenient stack-based holder for must-hold references.

Jon Watte před 10 roky
rodič
revize
083015e0fb
2 změnil soubory, kde provedl 37 přidání a 0 odebrání
  1. 2 0
      gameplay/src/Ref.cpp
  2. 35 0
      gameplay/src/Ref.h

+ 2 - 0
gameplay/src/Ref.cpp

@@ -32,11 +32,13 @@ Ref::~Ref()
 
 void Ref::addRef()
 {
+    GP_ASSERT(_refCount > 0 && _refCount < 1000000);
     ++_refCount;
 }
 
 void Ref::release()
 {
+    GP_ASSERT(_refCount > 0 && _refCount < 1000000);
     if ((--_refCount) <= 0)
     {
 #ifdef GP_USE_MEM_LEAK_DETECTION

+ 35 - 0
gameplay/src/Ref.h

@@ -43,6 +43,41 @@ public:
      */
     unsigned int getRefCount() const;
 
+    /**
+     * Temporarily hold a refcount on the stack, safely releasing when needed.
+     */
+    class Hold {
+        public:
+            /**
+             * Acquire and hold a reference to a given Ref object.
+             *
+             * The reference will go away when this object leaves scope.
+             */
+            Hold(Ref *r) : r_(r) {
+                r_->addRef();
+            }
+            ~Hold() {
+                if (r_) {
+                    r_->release();
+                }
+            }
+            Hold() = delete;
+            Hold(Hold const &) = delete;
+            Hold &operator=(Hold const &) = delete;
+
+            /**
+             * Remove the reference without releasing the object.
+             *
+             * @return the object, with the reference held.
+             */
+            Ref *unset() {
+                Ref *ret = r_;
+                r_ = nullptr;
+                return ret;
+            }
+        private:
+            Ref *r_;
+    };
 protected:
 
     /**