From 5c1b3ce42ef59448f641e9cc0a63e781c9f243b0 Mon Sep 17 00:00:00 2001 From: Itamar Date: Fri, 17 Apr 2020 13:41:45 +0300 Subject: [PATCH] AK: Allow having ref counted pointers to const object We allow the ref-counting parts of an object to be mutated even when the object itself is a const. An important detail is that we allow invoking 'will_be_destroyed' and 'one_ref_left', which are not required to be const qualified, on const objects. --- AK/RefCounted.h | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/AK/RefCounted.h b/AK/RefCounted.h index f453208601..12a21cc8cd 100644 --- a/AK/RefCounted.h +++ b/AK/RefCounted.h @@ -32,9 +32,9 @@ namespace AK { template -constexpr auto call_will_be_destroyed_if_present(T* object) -> decltype(object->will_be_destroyed(), TrueType {}) +constexpr auto call_will_be_destroyed_if_present(const T* object) -> decltype(object->will_be_destroyed(), TrueType {}) { - object->will_be_destroyed(); + const_cast(object)->will_be_destroyed(); return {}; } @@ -44,9 +44,9 @@ constexpr auto call_will_be_destroyed_if_present(...) -> FalseType } template -constexpr auto call_one_ref_left_if_present(T* object) -> decltype(object->one_ref_left(), TrueType {}) +constexpr auto call_one_ref_left_if_present(const T* object) -> decltype(object->one_ref_left(), TrueType {}) { - object->one_ref_left(); + const_cast(object)->one_ref_left(); return {}; } @@ -57,7 +57,7 @@ constexpr auto call_one_ref_left_if_present(...) -> FalseType class RefCountedBase { public: - void ref() + void ref() const { ASSERT(m_ref_count); ++m_ref_count; @@ -75,26 +75,26 @@ protected: ASSERT(!m_ref_count); } - void deref_base() + void deref_base() const { ASSERT(m_ref_count); --m_ref_count; } - int m_ref_count { 1 }; + mutable int m_ref_count { 1 }; }; template class RefCounted : public RefCountedBase { public: - void unref() + void unref() const { deref_base(); if (m_ref_count == 0) { - call_will_be_destroyed_if_present(static_cast(this)); - delete static_cast(this); + call_will_be_destroyed_if_present(static_cast(this)); + delete static_cast(this); } else if (m_ref_count == 1) { - call_one_ref_left_if_present(static_cast(this)); + call_one_ref_left_if_present(static_cast(this)); } } };