mirror of https://github.com/stenzek/duckstation
Common: ScopeGuard -> ScopedGuard
parent
13e3f2a179
commit
8af4f4f01a
@ -1,41 +0,0 @@
|
||||
// Copyright 2015 Dolphin Emulator Project
|
||||
// Licensed under GPLv2+
|
||||
// Refer to the license.txt file included.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <optional>
|
||||
|
||||
namespace Common
|
||||
{
|
||||
template <typename Callable>
|
||||
class ScopeGuard final
|
||||
{
|
||||
public:
|
||||
ScopeGuard(Callable&& finalizer) : m_finalizer(std::forward<Callable>(finalizer)) {}
|
||||
|
||||
ScopeGuard(ScopeGuard&& other) : m_finalizer(std::move(other.m_finalizer))
|
||||
{
|
||||
other.m_finalizer = nullptr;
|
||||
}
|
||||
|
||||
~ScopeGuard() { Exit(); }
|
||||
void Dismiss() { m_finalizer.reset(); }
|
||||
void Exit()
|
||||
{
|
||||
if (m_finalizer)
|
||||
{
|
||||
(*m_finalizer)(); // must not throw
|
||||
m_finalizer.reset();
|
||||
}
|
||||
}
|
||||
|
||||
ScopeGuard(const ScopeGuard&) = delete;
|
||||
|
||||
void operator=(const ScopeGuard&) = delete;
|
||||
|
||||
private:
|
||||
std::optional<Callable> m_finalizer;
|
||||
};
|
||||
|
||||
} // Namespace Common
|
@ -0,0 +1,35 @@
|
||||
#pragma once
|
||||
#include "types.h"
|
||||
#include <optional>
|
||||
#include <utility>
|
||||
|
||||
/// ScopedGuard provides an object which runs a function (usually a lambda) when
|
||||
/// it goes out of scope. This can be useful for releasing resources or handles
|
||||
/// which do not normally have C++ types to automatically release.
|
||||
template<typename T>
|
||||
class ScopedGuard final
|
||||
{
|
||||
public:
|
||||
ALWAYS_INLINE ScopedGuard(T&& func) : m_func(std::forward<T>(func)) {}
|
||||
ALWAYS_INLINE ScopedGuard(ScopedGuard&& other) : m_func(std::move(other.m_func)) { other.m_func = nullptr; }
|
||||
ALWAYS_INLINE ~ScopedGuard() { Invoke(); }
|
||||
|
||||
ScopedGuard(const ScopedGuard&) = delete;
|
||||
void operator=(const ScopedGuard&) = delete;
|
||||
|
||||
/// Prevents the function from being invoked when we go out of scope.
|
||||
ALWAYS_INLINE void Cancel() { m_func.reset(); }
|
||||
|
||||
/// Explicitly fires the function.
|
||||
ALWAYS_INLINE void Invoke()
|
||||
{
|
||||
if (!m_func.has_value())
|
||||
return;
|
||||
|
||||
m_func.value()();
|
||||
m_func.reset();
|
||||
}
|
||||
|
||||
private:
|
||||
std::optional<T> m_func;
|
||||
};
|
Loading…
Reference in New Issue