Arbutils/src/Memory/OptionalUniquePtr.hpp

76 lines
3.1 KiB
C++

#ifndef ARBUTILS_OPTIONALOptionalUniquePtr_HPP
#define ARBUTILS_OPTIONALOptionalUniquePtr_HPP
#include "../Assert.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* _raw;
public:
/// @brief Initialise a OptionalUniquePtr with a specific raw pointer.
inline OptionalUniquePtr<T>(__attribute__((nonnull)) T* ptr) : _raw(ptr){};
/// @brief Initialise a OptionalUniquePtr from a copy.
inline OptionalUniquePtr<T>(const OptionalUniquePtr<T>& other) : _raw(other._raw){};
/// @brief Initialise a OptionalUniquePtr with a std unique_ptr.
inline OptionalUniquePtr<T>(const std::unique_ptr<T>& other) : _raw(other.get()){};
~OptionalUniquePtr() noexcept { delete _raw; }
/// @brief Copy operator.
inline OptionalUniquePtr<T>& operator=(const OptionalUniquePtr<T>& rhs) {
if (this == &rhs)
return *this;
_raw = rhs._raw;
return *this;
}
inline OptionalUniquePtr<T>& operator=(__attribute__((nonnull)) T* rhs) {
if (_raw == &rhs)
return *this;
AssertNotNull(rhs);
_raw = rhs;
return *this;
}
/// @brief Operator for access into underlying pointer.
/// @warning Note that this asserts that the underlying pointer is not null first, to prevent segfaults.
inline T* operator->() const noexcept { return _raw; }
/// @brief Get the raw underlying pointer.
inline T* GetRaw() const noexcept { return _raw; }
/// @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* 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* rhs) const noexcept { return _raw == rhs; }
/// @brief Implicit cast to retrieve raw pointer.
inline operator T*() const noexcept {
AssertNotNull(_raw);
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