From 7a758c0e1c4fe1d47e8f7bc2c3a1261ffca24bdb Mon Sep 17 00:00:00 2001 From: Felix Morgner Date: Thu, 23 Jul 2026 01:50:51 +0200 Subject: kstd: add test for aliasing shared_ptr ctor --- libs/kstd/kstd/bits/shared_ptr.hpp | 1 - libs/kstd/kstd/bits/shared_ptr.tests.cpp | 61 ++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 libs/kstd/kstd/bits/shared_ptr.tests.cpp (limited to 'libs/kstd') diff --git a/libs/kstd/kstd/bits/shared_ptr.hpp b/libs/kstd/kstd/bits/shared_ptr.hpp index 1171d7fe..34332ace 100644 --- a/libs/kstd/kstd/bits/shared_ptr.hpp +++ b/libs/kstd/kstd/bits/shared_ptr.hpp @@ -392,7 +392,6 @@ namespace kstd //! @param other The shared_ptr to share ownership with. //! @param pointer The pointer this shared_ptr should own. template - requires bits::is_shared_pointer_ctor_compatible::value shared_ptr(shared_ptr const & other, T * pointer) noexcept : m_storage{pointer} , m_control_block{other.m_control_block} diff --git a/libs/kstd/kstd/bits/shared_ptr.tests.cpp b/libs/kstd/kstd/bits/shared_ptr.tests.cpp new file mode 100644 index 00000000..cf63e0aa --- /dev/null +++ b/libs/kstd/kstd/bits/shared_ptr.tests.cpp @@ -0,0 +1,61 @@ +#include + +#include + +namespace +{ + + struct base // NOLINT(cppcoreguidelines-virtual-class-destructor) + { + [[nodiscard]] virtual auto id() const noexcept -> int + { + return 1; + } + }; + + struct derived final : base + { + [[nodiscard]] auto id() const noexcept -> int override + { + return 2; + } + }; + +} // namespace + +SCENARIO("Shared pointer casts", "[kstd][shared_ptr]") +{ + GIVEN("a shared_ptr") + { + auto derived_ptr = kstd::make_shared(); + + WHEN("casting it to a shared_ptr via static_pointer_cast") + { + auto base_ptr = kstd::static_pointer_cast(derived_ptr); + + THEN("both pointer observer the same, still-derived object") + { + REQUIRE(base_ptr.get() == static_cast(derived_ptr.get())); + REQUIRE(base_ptr->id() == 2); + } + + THEN("ownership is shared") + { + REQUIRE(derived_ptr.use_count() == 2); + REQUIRE(base_ptr.use_count() == 2); + } + + AND_WHEN("the original shared pointer is reset") + { + derived_ptr.reset(); + + THEN("the object is kept alive by the aliased base shared pointer") + { + REQUIRE(base_ptr); + REQUIRE(base_ptr->id() == 2); + REQUIRE(base_ptr.use_count() == 1); + } + } + } + } +} -- cgit v1.2.3