2015-09-26 08:59:27 -06:00
|
|
|
// Copyright 2015 Dolphin Emulator Project
|
2021-07-04 19:22:19 -06:00
|
|
|
// SPDX-License-Identifier: GPL-2.0-or-later
|
2015-09-26 08:59:27 -06:00
|
|
|
|
|
|
|
#pragma once
|
|
|
|
|
2020-02-15 13:13:29 -07:00
|
|
|
#include <optional>
|
2015-09-26 08:59:27 -06:00
|
|
|
|
|
|
|
namespace Common
|
|
|
|
{
|
2020-02-15 13:13:29 -07:00
|
|
|
template <typename Callable>
|
2015-09-26 08:59:27 -06:00
|
|
|
class ScopeGuard final
|
|
|
|
{
|
|
|
|
public:
|
2020-02-15 13:13:29 -07:00
|
|
|
ScopeGuard(Callable&& finalizer) : m_finalizer(std::forward<Callable>(finalizer)) {}
|
2016-06-24 02:43:46 -06:00
|
|
|
|
|
|
|
ScopeGuard(ScopeGuard&& other) : m_finalizer(std::move(other.m_finalizer))
|
|
|
|
{
|
|
|
|
other.m_finalizer = nullptr;
|
|
|
|
}
|
|
|
|
|
|
|
|
~ScopeGuard() { Exit(); }
|
2020-02-15 13:13:29 -07:00
|
|
|
void Dismiss() { m_finalizer.reset(); }
|
2016-06-24 02:43:46 -06:00
|
|
|
void Exit()
|
|
|
|
{
|
|
|
|
if (m_finalizer)
|
|
|
|
{
|
2020-02-15 13:13:29 -07:00
|
|
|
(*m_finalizer)(); // must not throw
|
|
|
|
m_finalizer.reset();
|
2016-06-24 02:43:46 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
ScopeGuard(const ScopeGuard&) = delete;
|
|
|
|
|
|
|
|
void operator=(const ScopeGuard&) = delete;
|
2015-09-26 08:59:27 -06:00
|
|
|
|
|
|
|
private:
|
2020-02-15 13:13:29 -07:00
|
|
|
std::optional<Callable> m_finalizer;
|
2015-09-26 08:59:27 -06:00
|
|
|
};
|
|
|
|
|
|
|
|
} // Namespace Common
|