ladybird/AK/Weakable.h

54 lines
788 B
C
Raw Normal View History

2018-10-13 13:41:24 +00:00
#pragma once
#include "Assertions.h"
#include "RefPtr.h"
#include "RefCounted.h"
2018-10-13 13:41:24 +00:00
namespace AK {
template<typename T>
class Weakable;
template<typename T>
class WeakPtr;
2018-10-13 13:41:24 +00:00
template<typename T>
class WeakLink : public RefCounted<WeakLink<T>> {
2018-10-13 13:41:24 +00:00
friend class Weakable<T>;
2018-10-13 13:41:24 +00:00
public:
T* ptr() { return static_cast<T*>(m_ptr); }
const T* ptr() const { return static_cast<const T*>(m_ptr); }
private:
explicit WeakLink(T& weakable)
: m_ptr(&weakable)
{
}
T* m_ptr;
2018-10-13 13:41:24 +00:00
};
template<typename T>
class Weakable {
private:
class Link;
2018-10-13 13:41:24 +00:00
public:
WeakPtr<T> make_weak_ptr();
2018-10-13 13:41:24 +00:00
protected:
Weakable() {}
2018-10-13 13:41:24 +00:00
~Weakable()
{
if (m_link)
m_link->m_ptr = nullptr;
}
private:
RefPtr<WeakLink<T>> m_link;
2018-10-13 13:41:24 +00:00
};
}
using AK::Weakable;