]> git.ipfire.org Git - thirdparty/squid.git/commitdiff
Allow creation of RefCountable objects via Make() (#1458)
authorAmos Jeffries <yadij@users.noreply.github.com>
Thu, 31 Aug 2023 14:09:50 +0000 (14:09 +0000)
committerSquid Anubis <squid-anubis@squid-cache.org>
Thu, 31 Aug 2023 17:57:39 +0000 (17:57 +0000)
Compared to calling new() directly, using a Pointer-returning Make()
reduces memory leaks related to freshly allocated heap objects. Perfect
forwarding of constructor parameters through Make() minimizes overhead.

    const auto foo1 = new Foo(...); // XXX: leak-prone
    const auto foo2 = Foo::Pointer::Make(...); // OK

Future changes will prohibit RefCountable object creation via direct
new() calls and require using Make() or an equivalent safety API.

src/base/RefCount.h

index 782b9b52da4584ad37aa499acd1db9f519417d7d..1beb89248e495118ffa6c0f91e4d1b19b99f9dac 100644 (file)
@@ -15,6 +15,7 @@
 #include "base/Lock.h"
 
 #include <iostream>
+#include <utility>
 
 /**
  * Template for Reference Counting pointers.
@@ -27,6 +28,12 @@ class RefCount
 {
 
 public:
+    /// creates a new C object using given C constructor arguments (if any)
+    /// \returns a refcounting pointer to the created object
+    template<typename... Args>
+    inline static auto Make(Args&&... args) {
+        return RefCount<C>(new C(std::forward<Args>(args)...));
+    }
     RefCount () : p_ (nullptr) {}
 
     RefCount (C const *p) : p_(p) { reference (*this); }