From c9a35e104bd107dad027bcb35041d9835ddb2fae Mon Sep 17 00:00:00 2001 From: Andreas Kling Date: Thu, 9 Dec 2021 10:02:49 +0100 Subject: [PATCH] AK: Add RefCountForwarder This is a convenience template that implements reference count forwarding. This means that an object forwards ref() and unref() to another object. We can use this when two ref-counted objects need to keep each other alive. This situation poses two problems: - Using 2x RefPtr would cause a ref cycle and leak both objects. - Using 2x WeakPtr would allow one of them to be destroyed early. With RefCountForwarder, only one of the objects has a ref count. The object with the ref count points to the forwarding object by using a non-counting smart pointer (OwnPtr or NonnullOwnPtr). Thus, both objects are kept alive by the same ref count, and they can safely point to each other without worrying about disjoint lifetimes. --- AK/RefCountForwarder.h | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 AK/RefCountForwarder.h diff --git a/AK/RefCountForwarder.h b/AK/RefCountForwarder.h new file mode 100644 index 00000000000..c52360747ff --- /dev/null +++ b/AK/RefCountForwarder.h @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2021, Andreas Kling + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#pragma once + +namespace AK { + +template +class RefCountForwarder { +public: + void ref() { m_ref_count_target.ref(); } + void unref() { m_ref_count_target.unref(); } + + T& ref_count_target() { return m_ref_count_target; } + T const& ref_count_target() const { return m_ref_count_target; } + +protected: + RefCountForwarder(T& target) + : m_ref_count_target(target) + { + } + +private: + T& m_ref_count_target; +}; + +} + +using AK::RefCountForwarder;