SharedPtr: adopt_shared_from_owned
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
apio 2022-12-31 12:02:15 +01:00
parent 831711ab7e
commit df8f9c6cf6
Signed by: apio
GPG Key ID: B8A7D06E42258954
2 changed files with 19 additions and 0 deletions

View File

@ -2,6 +2,8 @@
#include <luna/Alloc.h> #include <luna/Alloc.h>
#include <luna/Result.h> #include <luna/Result.h>
template <typename T> class SharedPtr;
template <typename T> class OwnedPtr template <typename T> class OwnedPtr
{ {
public: public:
@ -38,6 +40,8 @@ template <typename T> class OwnedPtr
return *m_ptr; return *m_ptr;
} }
template <typename Type> friend Result<SharedPtr<Type>> adopt_shared_from_owned(OwnedPtr<Type>&&);
private: private:
T* m_ptr; T* m_ptr;
}; };

View File

@ -1,6 +1,7 @@
#pragma once #pragma once
#include <luna/Alloc.h> #include <luna/Alloc.h>
#include <luna/Atomic.h> #include <luna/Atomic.h>
#include <luna/OwnedPtr.h>
#include <luna/Result.h> #include <luna/Result.h>
#include <luna/ScopeGuard.h> #include <luna/ScopeGuard.h>
@ -118,4 +119,18 @@ template <typename T> Result<SharedPtr<T>> adopt_shared_if_nonnull(T* ptr)
if (ptr) return adopt_shared(ptr); if (ptr) return adopt_shared(ptr);
else else
return err(ENOMEM); return err(ENOMEM);
}
template <typename T> Result<SharedPtr<T>> adopt_shared_from_owned(OwnedPtr<T>&& other)
{
T* ptr = other.m_ptr;
other.m_ptr = nullptr;
auto guard = make_scope_guard([&] { delete ptr; });
SharedPtr<T> shared_ptr = TRY(adopt_shared(ptr));
guard.deactivate();
return shared_ptr;
} }