SharedPtr: Delete ptr on failure in all adopt_shared* functions

This commit is contained in:
apio 2023-02-03 22:19:26 +01:00
parent 38f0d3a4e6
commit be408c4cdb
Signed by: apio
GPG Key ID: B8A7D06E42258954

View File

@ -123,10 +123,18 @@ template <typename T> Result<SharedPtr<T>> adopt_shared(T* ptr)
return SharedPtr<T> { ptr, ref_count };
}
template <typename T, class... Args> Result<SharedPtr<T>> make_shared(Args... args)
// NOTE: ptr is deleted if any of the adopt_shared* functions fail to construct a SharedPtr.
template <typename T> Result<SharedPtr<T>> adopt_shared(T* ptr)
{
T* raw_ptr = TRY(make<T>(args...));
return adopt_shared(raw_ptr);
using RefCount = __detail::RefCount;
auto guard = make_scope_guard([ptr] { delete ptr; });
RefCount* const ref_count = TRY(make<RefCount>());
guard.deactivate();
return SharedPtr<T> { ptr, ref_count };
}
template <typename T> Result<SharedPtr<T>> adopt_shared_if_nonnull(T* ptr)