diff options
author | Itamar <itamar8910@gmail.com> | 2020-04-17 13:41:45 +0300 |
---|---|---|
committer | Andreas Kling <kling@serenityos.org> | 2020-04-20 17:25:50 +0200 |
commit | 5c1b3ce42ef59448f641e9cc0a63e781c9f243b0 (patch) | |
tree | 804069e016265547785d478d39f1d8c2409ab71a | |
parent | badbe8bc99a85d2c68877a706d9d51c217573357 (diff) | |
download | serenity-5c1b3ce42ef59448f641e9cc0a63e781c9f243b0.zip |
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.
-rw-r--r-- | AK/RefCounted.h | 22 |
1 files 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<class T> -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<T*>(object)->will_be_destroyed(); return {}; } @@ -44,9 +44,9 @@ constexpr auto call_will_be_destroyed_if_present(...) -> FalseType } template<class T> -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<T*>(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<typename T> 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<T*>(this)); - delete static_cast<T*>(this); + call_will_be_destroyed_if_present(static_cast<const T*>(this)); + delete static_cast<const T*>(this); } else if (m_ref_count == 1) { - call_one_ref_left_if_present(static_cast<T*>(this)); + call_one_ref_left_if_present(static_cast<const T*>(this)); } } }; |