Add EventHandle to manage smartptr based events more conveniently

This commit is contained in:
Georg Hagen
2025-02-28 16:47:22 +01:00
parent 3317fcac23
commit 6804436b4e
3 changed files with 60 additions and 15 deletions

View File

@@ -484,4 +484,55 @@ namespace OpenVulkano
{
return std::pair<std::weak_ptr<Instance>, Method>(instance, method);
}
class EventHandle
{
std::weak_ptr<void> m_owner;
IEventHandler* m_handler;
public:
EventHandle() : m_handler(nullptr) {}
EventHandle(const std::weak_ptr<void>& owner, IEventHandler* handler)
: m_owner(owner), m_handler(handler)
{}
EventHandle(const EventHandle& other) = delete;
EventHandle(EventHandle&& other) noexcept : m_owner(other.m_owner), m_handler(other.m_handler)
{
other.m_owner.reset();
other.m_handler = nullptr;
}
template<class EVENT_OWNER_T, typename... EVENT_ARGS, typename HANDLER_T>
EventHandle (const std::shared_ptr<EVENT_OWNER_T>& owner, Event<EVENT_ARGS...> EVENT_OWNER_T::* event, HANDLER_T&& handler)
: m_owner(owner), m_handler((owner.get()->*event).operator+=(handler))
{}
~EventHandle() { if (m_handler) Close(); }
void Close()
{
if (!m_handler) return;
if (auto acquired = m_owner.lock())
{
m_handler->SetInvalid();
}
m_handler = nullptr;
m_owner.reset();
}
EventHandle& operator =(const EventHandle& other) = delete;
EventHandle& operator =(EventHandle&& other) noexcept
{
Close();
m_owner.swap(other.m_owner);
std::swap(m_handler, other.m_handler);
return *this;
}
operator bool() const noexcept { return m_handler; }
};
}