ladybird/AK/ScopeGuard.h
Sam Atkins c86ad5c505 AK: Make ScopeGuard and ArmedScopeGuard [[nodiscard]]
Brought to you by a significant amount of pain and suffering, which this
would have prevented.
2025-01-09 18:36:34 +00:00

56 lines
853 B
C++

/*
* Copyright (c) 2018-2020, Andreas Kling <andreas@ladybird.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <AK/StdLibExtras.h>
namespace AK {
template<typename Callback>
class [[nodiscard]] ScopeGuard {
public:
ScopeGuard(Callback callback)
: m_callback(move(callback))
{
}
~ScopeGuard()
{
m_callback();
}
private:
Callback m_callback;
};
template<typename Callback>
class [[nodiscard]] ArmedScopeGuard {
public:
ArmedScopeGuard(Callback callback)
: m_callback(move(callback))
{
}
~ArmedScopeGuard()
{
if (m_armed)
m_callback();
}
void disarm() { m_armed = false; }
private:
Callback m_callback;
bool m_armed { true };
};
}
#if USING_AK_GLOBALLY
using AK::ArmedScopeGuard;
using AK::ScopeGuard;
#endif