59 assert(m_refs.load() == 0);
69 return m_refs.load(std::memory_order_relaxed);
74 return m_refs.fetch_add(1);
79 auto refs = m_refs.fetch_sub(1);
92 mutable std::atomic_int32_t m_refs{0};
96 static inline T* safe_ref(T*
object) {
103 static inline void unref(T*
object) {
122 m_object = safe_ref(
object);
126 m_object = safe_ref(other.m_object);
130 m_object = other.m_object;
131 other.m_object =
nullptr;
153 this->
reset(other.release());
158 return m_object == other.m_object;
161 return m_object != other.m_object;
165 return m_object ==
nullptr;
182 explicit operator bool()
const {
183 return m_object !=
nullptr;
187 reset(safe_ref(safe_ref_ptr));
207 return safe_ref(m_object);
211 [[nodiscard]]
bool is()
const {
212 return !m_object ||
dynamic_cast<G*
>(m_object);
222 auto casted =
dynamic_cast<G*
>(m_object);
224 if (!casted && m_object) {
225 throw std::runtime_error(
"failed to do dynamic cast");
233 return ref_ptr<G>(
dynamic_cast<G*
>(m_object));
242 T* m_object =
nullptr;
245 template<
typename T,
typename... TArgs>
247 return ref_ptr<T>(
new T(std::forward<TArgs>(args)...));
Base class for object with built-in reference counting mechanism.
Definition: ref.hpp:55
virtual ~RefCnt()
Definition: ref.hpp:57
bool is_unique() const
Definition: ref.hpp:64
std::int32_t get_refs() const
Definition: ref.hpp:68
std::int32_t add_ref() const
Definition: ref.hpp:72
std::int32_t rel_ref() const
Definition: ref.hpp:77
Automates reference counting and behaves as shared smart pointer.
Definition: ref.hpp:117
void acquire(T *safe_ref_ptr=nullptr)
Definition: ref.hpp:186
ref_ptr< T > & operator=(const ref_ptr &other)
Definition: ref.hpp:138
bool is_null() const
Definition: ref.hpp:164
ref_ptr(T *object)
Definition: ref.hpp:121
ref_ptr< T > & operator=(const ref_ptr< G > &other)
Definition: ref.hpp:145
T * ref_and_get()
Definition: ref.hpp:206
void reset(T *ptr=nullptr)
Definition: ref.hpp:190
T * release()
Definition: ref.hpp:196
T * operator->() const
Definition: ref.hpp:172
T * get() const
Definition: ref.hpp:202
bool operator==(const ref_ptr &other) const
Definition: ref.hpp:157
bool is() const
Definition: ref.hpp:211
T & operator*() const
Definition: ref.hpp:177
bool is_not_null() const
Definition: ref.hpp:168
ref_ptr< G > cast_static() const
Definition: ref.hpp:237
ref_ptr(ref_ptr &&other) noexcept
Definition: ref.hpp:129
~ref_ptr()
Definition: ref.hpp:133
ref_ptr(const ref_ptr &other)
Definition: ref.hpp:125
ref_ptr< G > cast_safe() const
Definition: ref.hpp:221
ref_ptr< G > as() const
Definition: ref.hpp:216
ref_ptr< G > cast() const
Definition: ref.hpp:232
bool operator!=(const ref_ptr &other) const
Definition: ref.hpp:160
ref_ptr< T > & operator=(ref_ptr &&other) noexcept
Definition: ref.hpp:151
ref_ptr< T > make_ref(TArgs &&... args)
Definition: ref.hpp:246
Definition: algorithm.hpp:37