yolobs-studio/plugins/mac-avcapture/scope-guard.hpp

70 lines
1.5 KiB
C++
Raw Normal View History

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