ladybird/AK/RefCountForwarder.h
Andreas Kling c9a35e104b AK: Add RefCountForwarder<T>
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.
2021-12-09 21:28:52 +01:00

33 lines
585 B
C++

/*
* Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
namespace AK {
template<typename T>
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;