Arbutils/src/Memory/BorrowedPtr.hpp

73 lines
2.5 KiB
C++
Raw Normal View History

#ifndef ARBUTILS_BORROWEDPTR_HPP
#define ARBUTILS_BORROWEDPTR_HPP
#include <memory>
#include "../Assert.hpp"
namespace ArbUt {
/// A borrowed pointer is used to indicate a pointer that is not owned by an object, but instead borrowed from
/// another owning object that is assumed to always be kept alive during the entire lifetime of the borrowing
/// object.
template <class T> class BorrowedPtr {
private:
T* _raw;
public:
inline BorrowedPtr<T>() noexcept : _raw(nullptr){};
inline BorrowedPtr<T>(T* ptr) noexcept : _raw(ptr){};
inline BorrowedPtr<T>(const BorrowedPtr<T>& other) noexcept : _raw(other._raw){};
inline BorrowedPtr<T>(const std::unique_ptr<T>& other) noexcept : _raw(other.get()){};
~BorrowedPtr() noexcept = default;
inline BorrowedPtr<T>& operator=(const BorrowedPtr<T>& rhs) noexcept {
_raw = rhs._raw;
return *this;
}
inline T* operator->() const noexcept {
AssertNotNull(_raw);
return _raw;
}
inline T operator*() const noexcept {
AssertNotNull(_raw);
return *_raw;
}
inline T* GetRaw() const noexcept { return _raw; }
inline bool operator==(const BorrowedPtr& rhs) const noexcept { return _raw == rhs._raw; }
inline bool operator!=(const BorrowedPtr& rhs) const noexcept { return _raw != rhs._raw; }
[[nodiscard]] inline constexpr bool IsNull() const noexcept { return _raw == nullptr; }
inline BorrowedPtr<const T> Const() const noexcept { return BorrowedPtr<const T>(_raw); }
template <class TCast> inline BorrowedPtr<TCast> As() const {
auto cast = dynamic_cast<TCast*>(_raw);
return BorrowedPtr<TCast>(cast);
}
template <class TCast> inline bool TryAs(BorrowedPtr<TCast>& out) const noexcept {
auto cast = dynamic_cast<TCast*>(_raw);
if (cast == nullptr)
return false;
out = BorrowedPtr<TCast>(cast);
return true;
}
template <class TCast> inline BorrowedPtr<TCast> ForceAs() const noexcept {
auto cast = reinterpret_cast<TCast*>(_raw);
return BorrowedPtr<TCast>(cast);
}
};
}
2020-06-02 14:03:47 +00:00
namespace std {
template <class T> struct hash<ArbUt::BorrowedPtr<T>> {
std::size_t operator()(const ArbUt::BorrowedPtr<T>& k) const { return (size_t)k.GetRaw(); }
};
}
#endif // ARBUTILS_BORROWEDPTR_HPP