1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-05-14 16:24:57 +00:00

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.
This commit is contained in:
Itamar 2020-04-17 13:41:45 +03:00 committed by Andreas Kling
parent badbe8bc99
commit 5c1b3ce42e

View file

@ -32,9 +32,9 @@
namespace AK { namespace AK {
template<class T> 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 {}; return {};
} }
@ -44,9 +44,9 @@ constexpr auto call_will_be_destroyed_if_present(...) -> FalseType
} }
template<class T> 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 {}; return {};
} }
@ -57,7 +57,7 @@ constexpr auto call_one_ref_left_if_present(...) -> FalseType
class RefCountedBase { class RefCountedBase {
public: public:
void ref() void ref() const
{ {
ASSERT(m_ref_count); ASSERT(m_ref_count);
++m_ref_count; ++m_ref_count;
@ -75,26 +75,26 @@ protected:
ASSERT(!m_ref_count); ASSERT(!m_ref_count);
} }
void deref_base() void deref_base() const
{ {
ASSERT(m_ref_count); ASSERT(m_ref_count);
--m_ref_count; --m_ref_count;
} }
int m_ref_count { 1 }; mutable int m_ref_count { 1 };
}; };
template<typename T> template<typename T>
class RefCounted : public RefCountedBase { class RefCounted : public RefCountedBase {
public: public:
void unref() void unref() const
{ {
deref_base(); deref_base();
if (m_ref_count == 0) { if (m_ref_count == 0) {
call_will_be_destroyed_if_present(static_cast<T*>(this)); call_will_be_destroyed_if_present(static_cast<const T*>(this));
delete static_cast<T*>(this); delete static_cast<const T*>(this);
} else if (m_ref_count == 1) { } 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));
} }
} }
}; };