From 7151b0e5bcabb0216e79e742ae13c4f429ec2011 Mon Sep 17 00:00:00 2001 From: rtk0c Date: Sat, 27 Apr 2024 10:06:05 -0700 Subject: Commit misc work from a while ago --- src/brussel.common/ScopedResource.hpp | 54 +++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 src/brussel.common/ScopedResource.hpp (limited to 'src/brussel.common/ScopedResource.hpp') diff --git a/src/brussel.common/ScopedResource.hpp b/src/brussel.common/ScopedResource.hpp new file mode 100644 index 0000000..b4098eb --- /dev/null +++ b/src/brussel.common/ScopedResource.hpp @@ -0,0 +1,54 @@ +#pragma once + +#include + +/// std::unique_ptr, but for non-pointer resources +template + requires std::is_trivial_v && std::equality_comparable +class ScopedResource { +private: + T mValue; + +public: + ScopedResource() + : mValue{ kNullValue } {} + explicit ScopedResource(T t) + : mValue{ std::move(t) } {} + + ScopedResource(const ScopedResource& that) = delete; + ScopedResource& operator=(const ScopedResource& that) = delete; + + ScopedResource(ScopedResource&& that) noexcept + : mValue(that.mValue) {} + ScopedResource& operator=(ScopedResource&& that) noexcept { + if (this == &that) + return *this; + TDeleter::DeleteObject(mValue); + mValue = that.mValue; + that.mValue = kNullValue; + return *this; + } + + ScopedResource& operator=(T newValue) { + TDeleter::DeleteObject(mValue); + mValue = newValue; + return *this; + } + + ~ScopedResource() { + TDeleter::DeleteObject(mValue); + } + + explicit operator bool() const { + return mValue != kNullValue; + } + + const T& get() const { return mValue; } + T& get() { return mValue; } + + T release() { + T tmp = mValue; + mValue = kNullValue; + return tmp; + } +}; -- cgit v1.2.3-70-g09d2