diff options
author | rtk0c <[email protected]> | 2024-04-27 10:06:05 -0700 |
---|---|---|
committer | rtk0c <[email protected]> | 2024-04-27 10:06:05 -0700 |
commit | 7151b0e5bcabb0216e79e742ae13c4f429ec2011 (patch) | |
tree | ef5d9d370a5c1956a27f5da06b839133913169e9 /src/brussel.common/ScopedResource.hpp | |
parent | 611008e9a7f262ca5ef7c5c89a04705ed706f7a2 (diff) |
Commit misc work from a while ago
Diffstat (limited to 'src/brussel.common/ScopedResource.hpp')
-rw-r--r-- | src/brussel.common/ScopedResource.hpp | 54 |
1 files changed, 54 insertions, 0 deletions
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 <type_traits> + +/// std::unique_ptr, but for non-pointer resources +template <typename T, typename TDeleter, T kNullValue = T()> + requires std::is_trivial_v<T> && std::equality_comparable<T> +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; + } +}; |