From 620810d720d1942a1daf34e600e607d0122dc4df Mon Sep 17 00:00:00 2001 From: apio Date: Fri, 3 Feb 2023 22:19:26 +0100 Subject: [PATCH] SharedPtr: Delete ptr on failure in all adopt_shared* functions --- luna/include/luna/SharedPtr.h | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/luna/include/luna/SharedPtr.h b/luna/include/luna/SharedPtr.h index 020c37a5..2ddf3b5d 100644 --- a/luna/include/luna/SharedPtr.h +++ b/luna/include/luna/SharedPtr.h @@ -123,10 +123,18 @@ template Result> adopt_shared(T* ptr) return SharedPtr { ptr, ref_count }; } -template Result> make_shared(Args... args) +// NOTE: ptr is deleted if any of the adopt_shared* functions fail to construct a SharedPtr. +template Result> adopt_shared(T* ptr) { - T* raw_ptr = TRY(make(args...)); - return adopt_shared(raw_ptr); + using RefCount = __detail::RefCount; + + auto guard = make_scope_guard([ptr] { delete ptr; }); + + RefCount* const ref_count = TRY(make()); + + guard.deactivate(); + + return SharedPtr { ptr, ref_count }; } template Result> adopt_shared_if_nonnull(T* ptr)