2015-08-18 11:00:55 -07:00
|
|
|
/*
|
|
|
|
* Based on Loki::ScopeGuard
|
|
|
|
*/
|
|
|
|
|
|
|
|
#pragma once
|
|
|
|
|
|
|
|
#include <utility>
|
|
|
|
|
|
|
|
namespace scope_guard_util {
|
|
|
|
|
2019-06-22 22:13:45 -07:00
|
|
|
template<typename FunctionType> class ScopeGuard {
|
2015-08-18 11:00:55 -07:00
|
|
|
public:
|
2019-06-22 22:13:45 -07:00
|
|
|
void dismiss() noexcept { dismissed_ = true; }
|
2015-08-18 11:00:55 -07:00
|
|
|
|
2019-06-22 22:13:45 -07:00
|
|
|
explicit ScopeGuard(const FunctionType &fn) : function_(fn) {}
|
2015-08-18 11:00:55 -07:00
|
|
|
|
2019-06-22 22:13:45 -07:00
|
|
|
explicit ScopeGuard(FunctionType &&fn) : function_(std::move(fn)) {}
|
2015-08-18 11:00:55 -07:00
|
|
|
|
|
|
|
ScopeGuard(ScopeGuard &&other)
|
|
|
|
: dismissed_(other.dismissed_),
|
|
|
|
function_(std::move(other.function_))
|
|
|
|
{
|
|
|
|
other.dismissed_ = true;
|
|
|
|
}
|
|
|
|
|
|
|
|
~ScopeGuard() noexcept
|
|
|
|
{
|
|
|
|
if (!dismissed_)
|
|
|
|
execute();
|
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
2019-06-22 22:13:45 -07:00
|
|
|
void *operator new(size_t) = delete;
|
2015-08-18 11:00:55 -07:00
|
|
|
|
2019-06-22 22:13:45 -07:00
|
|
|
void execute() noexcept { function_(); }
|
2015-08-18 11:00:55 -07:00
|
|
|
|
|
|
|
bool dismissed_ = false;
|
|
|
|
FunctionType function_;
|
|
|
|
};
|
|
|
|
|
2019-06-22 22:13:45 -07:00
|
|
|
template<typename FunctionType>
|
2015-08-18 11:00:55 -07:00
|
|
|
ScopeGuard<typename std::decay<FunctionType>::type>
|
|
|
|
make_guard(FunctionType &&fn)
|
|
|
|
{
|
|
|
|
return ScopeGuard<typename std::decay<FunctionType>::type>{
|
2019-06-22 22:13:45 -07:00
|
|
|
std::forward<FunctionType>(fn)};
|
2015-08-18 11:00:55 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
namespace detail {
|
|
|
|
|
|
|
|
enum class ScopeGuardOnExit {};
|
|
|
|
|
2019-06-22 22:13:45 -07:00
|
|
|
template<typename FunctionType>
|
2015-08-18 11:00:55 -07:00
|
|
|
ScopeGuard<typename std::decay<FunctionType>::type>
|
2019-06-22 22:13:45 -07:00
|
|
|
operator+(detail::ScopeGuardOnExit, FunctionType &&fn)
|
|
|
|
{
|
|
|
|
return ScopeGuard<typename std::decay<FunctionType>::type>(
|
|
|
|
std::forward<FunctionType>(fn));
|
2015-08-18 11:00:55 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
} // namespace scope_guard_util
|
|
|
|
|
2019-06-22 22:13:45 -07:00
|
|
|
#define SCOPE_EXIT_CONCAT2(x, y) x##y
|
2015-08-18 11:00:55 -07:00
|
|
|
#define SCOPE_EXIT_CONCAT(x, y) SCOPE_EXIT_CONCAT2(x, y)
|
2019-06-22 22:13:45 -07:00
|
|
|
#define SCOPE_EXIT \
|
2015-08-18 11:00:55 -07:00
|
|
|
auto SCOPE_EXIT_CONCAT(SCOPE_EXIT_STATE, __LINE__) = \
|
|
|
|
::scope_guard_util::detail::ScopeGuardOnExit() + [&]() noexcept
|