From 60ccc62f4934e44ad5b905fdbcf458302b8d8a09 Mon Sep 17 00:00:00 2001 From: rtk0c Date: Fri, 3 Jun 2022 23:26:44 -0700 Subject: Changeset: 63 [WIP] Rename directories --- source/Common/RcPtr.hpp | 120 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 120 insertions(+) create mode 100644 source/Common/RcPtr.hpp (limited to 'source/Common/RcPtr.hpp') diff --git a/source/Common/RcPtr.hpp b/source/Common/RcPtr.hpp new file mode 100644 index 0000000..130b2b2 --- /dev/null +++ b/source/Common/RcPtr.hpp @@ -0,0 +1,120 @@ +#pragma once + +#include "Macros.hpp" +#include "TypeTraits.hpp" + +#include +#include +#include +#include + +class RefCounted { +public: + // DO NOT MODIFY this field, unless explicitly documented the use + uint32_t refCount = 0; + uint32_t weakCount = 0; // TODO implement +}; + +template > +class RcPtr : TDeleter { +private: + static_assert(std::is_base_of_v); + T* mPtr; + +public: + RcPtr() + : mPtr{ nullptr } { + } + + explicit RcPtr(T* ptr) + : mPtr{ ptr } { + if (ptr) { + ++ptr->RefCounted::refCount; + } + } + + ~RcPtr() { + CleanUp(); + } + + void Attach(T* ptr) { + CleanUp(); + mPtr = ptr; + if (ptr) { + ++ptr->RefCounted::refCount; + } + } + + void Detatch() { + CleanUp(); + mPtr = nullptr; + } + + RcPtr(const RcPtr& that) + : mPtr{ that.mPtr } { + if (mPtr) { + ++mPtr->RefCounted::refCount; + } + } + + RcPtr& operator=(const RcPtr& that) { + CleanUp(); + mPtr = that.mPtr; + if (mPtr) { + ++mPtr->RefCounted::refCount; + } + return *this; + } + + RcPtr(RcPtr&& that) + : mPtr{ that.mPtr } { + that.mPtr = nullptr; + } + + RcPtr& operator=(RcPtr&& that) { + CleanUp(); + mPtr = that.mPtr; + that.mPtr = nullptr; + return *this; + } + + template + requires std::is_base_of_v + operator RcPtr() const { + return RcPtr(mPtr); + } + + bool operator==(std::nullptr_t ptr) const { + return mPtr == nullptr; + } + + bool operator==(const T* ptr) const { + return mPtr == ptr; + } + + bool operator==(T* ptr) const { + return mPtr == ptr; + } + + template + bool operator==(const RcPtr& ptr) const { + return mPtr == ptr.Get(); + } + + T* Get() const { + return mPtr; + } + + T& operator*() const { return *mPtr; } + T* operator->() const { return mPtr; } + +private: + void CleanUp() { + if (mPtr) { + --mPtr->RefCounted::refCount; + if (mPtr->RefCounted::refCount == 0) { + TDeleter::operator()(mPtr); + } + } + } +}; -- cgit v1.2.3-70-g09d2