From 8794cdc99d80241f134966a3b74b09a1daab7a71 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Steven=20Dee=20=28J=C5=8Dshin=29?= Date: Mon, 17 Jun 2024 21:47:04 -0700 Subject: [PATCH] Try moving the unique_ptr into shared_pointer __::shared_pointer::make takes ownership of p the same way as shared_ptr does: either the allocation succeeds and the returned control block owns it, or the allocation throws and the unique_ptr frees it. Note that this construction is safe since C++17, in which the evaluation of constructor arguments is sequenced after a new-expression allocation. --- ctl/shared_ptr.h | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/ctl/shared_ptr.h b/ctl/shared_ptr.h index 2cbd56b44..b562a5a49 100644 --- a/ctl/shared_ptr.h +++ b/ctl/shared_ptr.h @@ -48,7 +48,9 @@ struct shared_pointer : shared_control static shared_pointer* make(T* p) { - return new shared_pointer(p); + auto p2 = unique_ptr(p); + auto r = new shared_pointer(p2.release()); + return r; } private: @@ -85,11 +87,8 @@ class shared_ptr : p(nullptr), ctl(nullptr) { } - shared_ptr(T* const p2) + shared_ptr(T* const p) : p(p), ctl(__::shared_pointer::make(p)) { - auto hold = ctl::unique_ptr(p2); - ctl = __::shared_pointer::make(p2); - p = hold.release(); } ~shared_ptr()