Luna/luna/include/luna/OwnedPtr.h

65 lines
1.1 KiB
C
Raw Normal View History

2022-12-23 09:23:13 +00:00
#pragma once
#include <luna/Alloc.h>
#include <luna/Result.h>
2022-12-31 11:02:15 +00:00
template <typename T> class SharedPtr;
2022-12-23 09:23:13 +00:00
template <typename T> class OwnedPtr
{
public:
OwnedPtr(T* ptr)
{
m_ptr = ptr;
}
~OwnedPtr()
{
if (m_ptr) delete m_ptr;
}
OwnedPtr(const OwnedPtr<T>& other) = delete;
OwnedPtr(OwnedPtr<T>&& other)
{
m_ptr = other.m_ptr;
other.m_ptr = nullptr;
}
T* ptr() const
{
return m_ptr;
}
T* operator->() const
{
return m_ptr;
}
T& operator*() const
{
return *m_ptr;
}
2022-12-31 11:02:15 +00:00
template <typename Type> friend Result<SharedPtr<Type>> adopt_shared_from_owned(OwnedPtr<Type>&&);
2022-12-23 09:23:13 +00:00
private:
T* m_ptr;
};
template <typename T, class... Args> Result<OwnedPtr<T>> make_owned(Args... args)
{
T* raw = TRY(make<T>(args...));
return OwnedPtr<T> { raw };
}
template <typename T> OwnedPtr<T> adopt_owned(T* ptr)
{
return OwnedPtr<T> { ptr };
}
template <typename T> Result<OwnedPtr<T>> adopt_owned_if_nonnull(T* ptr)
{
if (ptr) return OwnedPtr<T> { ptr };
else
return err(ENOMEM);
}