From: Amos Jeffries Date: Thu, 31 Aug 2023 14:09:50 +0000 (+0000) Subject: Allow creation of RefCountable objects via Make() (#1458) X-Git-Tag: SQUID_7_0_1~362 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=3e50f1af739a198888309ba48dee0a7044fbf0b1;p=thirdparty%2Fsquid.git Allow creation of RefCountable objects via Make() (#1458) 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. --- diff --git a/src/base/RefCount.h b/src/base/RefCount.h index 782b9b52da..1beb89248e 100644 --- a/src/base/RefCount.h +++ b/src/base/RefCount.h @@ -15,6 +15,7 @@ #include "base/Lock.h" #include +#include /** * 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 + inline static auto Make(Args&&... args) { + return RefCount(new C(std::forward(args)...)); + } RefCount () : p_ (nullptr) {} RefCount (C const *p) : p_(p) { reference (*this); }