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