#ifndef RFL_REF_HPP_ #define RFL_REF_HPP_ #include #include namespace rfl { /// The Ref class behaves very similarly to the shared_ptr, but unlike the /// shared_ptr, it is 100% guaranteed to be filled at all times. template class Ref { public: /// The default way of creating new references is /// Ref::make(...) or make_ref(...). template static Ref make(Args&&... _args) { return Ref(std::make_shared(std::forward(_args)...)); } Ref() : ptr_(std::make_shared()) {} Ref(const Ref& _other) = default; Ref(Ref&& _other) = default; template , bool>::type = true> Ref(const Ref& _other) : ptr_(_other.ptr()) {} template , bool>::type = true> Ref(Ref&& _other) noexcept : ptr_(std::make_shared(std::forward(*_other))) {} ~Ref() = default; /// Returns a pointer to the underlying object T* get() const { return ptr_.get(); } /// Returns the underlying object. T& operator*() { return *ptr_; } /// Returns the underlying object. T& operator*() const { return *ptr_; } /// Returns the underlying object. T* operator->() { return ptr_.get(); } /// Returns the underlying object. T* operator->() const { return ptr_.get(); } /// Returns the underlying shared_ptr const std::shared_ptr& ptr() const { return ptr_; } /// Copy assignment operator. template , bool>::type = true> Ref& operator=(const Ref& _other) { ptr_ = _other.ptr(); return *this; } /// Move assignment operator template , bool>::type = true> Ref& operator=(Ref&& _other) noexcept { ptr_ = std::make_shared(std::forward(*_other)); return *this; } /// Move assignment operator Ref& operator=(Ref&& _other) noexcept = default; /// Copy assignment operator Ref& operator=(const Ref& _other) = default; private: /// Only make is allowed to use this constructor. explicit Ref(std::shared_ptr&& _ptr) : ptr_(std::move(_ptr)) {} private: /// The underlying shared_ptr_ std::shared_ptr ptr_; }; /// Generates a new Ref. template Ref make_ref(Args&&... _args) { return Ref::make(std::forward(_args)...); } template inline auto operator<=>(const Ref& _t1, const Ref& _t2) { return _t1.ptr() <=> _t2.ptr(); } template inline std::basic_ostream& operator<<( std::basic_ostream& _os, const Ref& _b) { _os << _b.get(); return _os; } } // namespace rfl #endif // RFL_REF_HPP_