mirror of
https://github.com/LadybirdBrowser/ladybird.git
synced 2024-08-16 17:00:35 +03:00
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.
This commit is contained in:
parent
fed6a76990
commit
c9a35e104b
Notes:
sideshowbarker
2024-07-17 23:03:17 +09:00
Author: https://github.com/awesomekling Commit: https://github.com/SerenityOS/serenity/commit/c9a35e104bd
32
AK/RefCountForwarder.h
Normal file
32
AK/RefCountForwarder.h
Normal file
@ -0,0 +1,32 @@
|
||||
/*
|
||||
* 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;
|
Loading…
Reference in New Issue
Block a user