mijin2/source/mijin/util/scope_guard.hpp

44 lines
1.1 KiB
C++

#pragma once
#if !defined(MIJIN_UTIL_SCOPE_GUARD_HPP_INCLUDED)
#define MIJIN_UTIL_SCOPE_GUARD_HPP_INCLUDED 1
#include <functional>
#include "./common_macros.hpp"
#include "../internal/common.hpp"
#define MIJIN_SCOPE_EXIT_NAMED(name) \
const mijin::ScopeExitGuard name = [&]()
#define MIJIN_SCOPE_EXIT MIJIN_SCOPE_EXIT_NAMED(MIJIN_CONCAT(MIJIN_CONCAT(scope_guard_, __LINE__), __))
namespace mijin
{
class ScopeExitGuard
{
private:
mutable std::function<void(void)> func; // variable is declared const to make clang-tidy happy, but we still want to be able to reset()
public:
template<typename TFunc>
inline ScopeExitGuard(TFunc&& func_) MIJIN_NOEXCEPT : func(std::forward<TFunc>(func_)) {}
ScopeExitGuard(const ScopeExitGuard&) = delete;
ScopeExitGuard(ScopeExitGuard&&) = delete;
inline ~ScopeExitGuard() MIJIN_NOEXCEPT
{
if (func) {
func();
}
}
ScopeExitGuard& operator=(const ScopeExitGuard&) = delete;
ScopeExitGuard& operator=(ScopeExitGuard&&) = delete;
inline void reset() const MIJIN_NOEXCEPT
{
func = {};
}
};
}
#endif // defined(MIJIN_UTIL_SCOPE_GUARD_HPP_INCLUDED)