From d9b35fab190b3bcae2b05ca990822546d660ff20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Steven=20Dee=20=28J=C5=8Dshin=29?= Date: Tue, 27 Aug 2024 21:15:39 -0700 Subject: [PATCH] make_shared alloc optimization --- ctl/shared_ptr.h | 44 ++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 40 insertions(+), 4 deletions(-) diff --git a/ctl/shared_ptr.h b/ctl/shared_ptr.h index da112ff19..7b1080097 100644 --- a/ctl/shared_ptr.h +++ b/ctl/shared_ptr.h @@ -80,7 +80,7 @@ class shared_ref } private: - virtual void dispose() = 0; + virtual void dispose() noexcept = 0; size_t shared = 0; size_t weak = 0; @@ -102,7 +102,7 @@ class shared_pointer : public shared_ref { } - void dispose() override + void dispose() noexcept override { move(d)(p); } @@ -111,6 +111,35 @@ class shared_pointer : public shared_ref [[no_unique_address]] D d; }; +template +class shared_emplace : public shared_ref +{ + public: + union + { + T t; + }; + + template + void construct(Args&&... args) + { + ::new (&t) T(forward(args)...); + } + + static unique_ptr make() + { + return unique_ptr(new shared_emplace()); + } + + private: + explicit constexpr shared_emplace() noexcept = default; + + void dispose() noexcept override + { + t.~T(); + } +}; + template concept shared_ptr_convertible = is_convertible_v || is_void_v; @@ -302,6 +331,9 @@ class shared_ptr template friend class shared_ptr; + template + friend shared_ptr make_shared(Args&&... args); + element_type* p = nullptr; __::shared_ref* rc = nullptr; }; @@ -385,8 +417,12 @@ template shared_ptr make_shared(Args&&... args) { - // TODO(mrdomino): shared_emplace - return shared_ptr(new T(forward(args)...)); + auto rc = __::shared_emplace::make(); + rc->construct(forward(args)...); + shared_ptr r; + r.p = &rc->t; + r.rc = rc.release(); + return r; } } // namespace ctl