From df8f9c6cf614e719eaf2463ef0b72641acc08572 Mon Sep 17 00:00:00 2001 From: apio Date: Sat, 31 Dec 2022 12:02:15 +0100 Subject: [PATCH] SharedPtr: adopt_shared_from_owned --- luna/include/luna/OwnedPtr.h | 4 ++++ luna/include/luna/SharedPtr.h | 15 +++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/luna/include/luna/OwnedPtr.h b/luna/include/luna/OwnedPtr.h index cc147f24..0f76630d 100644 --- a/luna/include/luna/OwnedPtr.h +++ b/luna/include/luna/OwnedPtr.h @@ -2,6 +2,8 @@ #include #include +template class SharedPtr; + template class OwnedPtr { public: @@ -38,6 +40,8 @@ template class OwnedPtr return *m_ptr; } + template friend Result> adopt_shared_from_owned(OwnedPtr&&); + private: T* m_ptr; }; diff --git a/luna/include/luna/SharedPtr.h b/luna/include/luna/SharedPtr.h index 4cf1bcff..6a9caffd 100644 --- a/luna/include/luna/SharedPtr.h +++ b/luna/include/luna/SharedPtr.h @@ -1,6 +1,7 @@ #pragma once #include #include +#include #include #include @@ -118,4 +119,18 @@ template Result> adopt_shared_if_nonnull(T* ptr) if (ptr) return adopt_shared(ptr); else return err(ENOMEM); +} + +template Result> adopt_shared_from_owned(OwnedPtr&& other) +{ + T* ptr = other.m_ptr; + other.m_ptr = nullptr; + + auto guard = make_scope_guard([&] { delete ptr; }); + + SharedPtr shared_ptr = TRY(adopt_shared(ptr)); + + guard.deactivate(); + + return shared_ptr; } \ No newline at end of file