Arbutils/src/Memory/__OptionalUniquePtr.hpp

75 lines
3.1 KiB
C++

#ifndef ARBUTILS_OPTIONALOptionalUniquePtr_HPP
#define ARBUTILS_OPTIONALOptionalUniquePtr_HPP
#include "../Ensure.hpp"
#include "../Misc.hpp"
namespace ArbUt {
/// @brief An optional unique pointer is used to indicate a pointer that is owned by its holder, and will be deleted
/// when its owner is deleted.
/// @details A unique pointer is used to indicate a pointer that is owned by an object, and that needs to be deleted
/// when its owner is deleted.
template <class T> class OptionalUniquePtr {
private:
T* nullable _raw;
public:
/// @brief Initialise a BorrowedPtr with a nullptr.
inline OptionalUniquePtr<T>() : _raw(nullptr) {}
/// @brief Initialise a OptionalUniquePtr with a specific raw pointer.
inline OptionalUniquePtr<T>(T* nullable ptr) : _raw(ptr){};
/// @brief We do not allow copying or moving of unique pointers, as that would cause memory leaks and use after
/// frees.
NO_COPY_OR_MOVE(OptionalUniquePtr);
~OptionalUniquePtr() noexcept { delete _raw; }
/// @brief Return whether the pointer is null or not.
[[nodiscard]] inline bool HasValue() const noexcept { return _raw != nullptr; }
/// @brief Get the raw underlying pointer, and take ownership of it. This removes the existing pointer in here.
inline T* nullable TakeOwnership() noexcept {
auto raw = _raw;
_raw = nullptr;
return raw;
}
/// @brief Get the raw underlying pointer.
inline T* nullable GetValue() const noexcept { return _raw; }
/// @brief Assign operator with raw pointer.
inline OptionalUniquePtr<T>& operator=(T* nullable rhs) {
if (_raw == rhs) {
return *this;
}
_raw = rhs;
return *this;
}
/// @brief Check equality of two OptionalUniquePtr objects
inline bool operator==(const OptionalUniquePtr& rhs) const noexcept { return _raw == rhs._raw; }
/// @brief Check equality of pointers
inline bool operator==(T* nullable rhs) const noexcept { return _raw == rhs; }
/// @brief Check equality of two OptionalUniquePtr objects
inline bool operator!=(const OptionalUniquePtr& rhs) const noexcept { return _raw != rhs._raw; }
/// @brief Check equality of pointers
inline bool operator!=(T* nullable rhs) const noexcept { return _raw != rhs; }
/// @brief Implicit cast to retrieve raw pointer.
inline operator T* nullable() const noexcept { return _raw; }
};
}
namespace std {
/// @brief Helper class for allowing hashing of OptionalUniquePtr.
template <class T> struct hash<ArbUt::OptionalUniquePtr<T>> {
/// @brief Returns a hash of for a borrowed Pointer. Effectively just the raw memory address.
/// @param k A borrowed pointer.
/// @return The hash of the borrowed pointer.
std::size_t operator()(const ArbUt::OptionalUniquePtr<T>& k) const { return (size_t)k.GetRaw(); }
};
}
#endif // ARBUTILS_OPTIONALOptionalUniquePtr_HPP