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