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.
This commit is contained in:
Steven Dee (Jōshin) 2024-06-17 21:47:04 -07:00
parent d8ee0130e2
commit 8794cdc99d
No known key found for this signature in database

View file

@ -48,7 +48,9 @@ struct shared_pointer : shared_control
static shared_pointer* make(T* p) static shared_pointer* make(T* p)
{ {
return new shared_pointer(p); auto p2 = unique_ptr<T>(p);
auto r = new shared_pointer(p2.release());
return r;
} }
private: private:
@ -85,11 +87,8 @@ class shared_ptr
: p(nullptr), ctl(nullptr) : p(nullptr), ctl(nullptr)
{ {
} }
shared_ptr(T* const p2) shared_ptr(T* const p) : p(p), ctl(__::shared_pointer<T>::make(p))
{ {
auto hold = ctl::unique_ptr(p2);
ctl = __::shared_pointer<T>::make(p2);
p = hold.release();
} }
~shared_ptr() ~shared_ptr()