Skip to content

Instantly share code, notes, and snippets.

@mmozeiko
Created August 8, 2014 22:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mmozeiko/b22f86d3fb08b544e839 to your computer and use it in GitHub Desktop.
Save mmozeiko/b22f86d3fb08b544e839 to your computer and use it in GitHub Desktop.
#pragma once
template <class Fun>
class ScopeGuard
{
private:
Fun f;
bool active;
public:
ScopeGuard(Fun f)
: f(std::move(f))
, active(true)
{
}
~ScopeGuard()
{
if (active)
{
f();
}
}
void dismiss()
{
active = false;
}
ScopeGuard() = delete;
ScopeGuard(const ScopeGuard&) = delete;
ScopeGuard& operator = (const ScopeGuard&) = delete;
ScopeGuard(ScopeGuard&& rhs)
:f(std::move(rhs.f))
, active_(rhs.active)
{
rhs.dismiss();
}
};
template <class Fun>
ScopeGuard<Fun> scopeGuard(Fun f)
{
return ScopeGuard<Fun>(std::move(f));
}
namespace detail
{
enum class ScopeGuardOnExit {};
template <typename Fun>
ScopeGuard<Fun> operator + (ScopeGuardOnExit, Fun&& fn)
{
return ScopeGuard<Fun>(std::forward<Fun>(fn));
}
}
#define SCOPE_GUARD_CONCATENATE_IMPL(s1, s2) s1##s2
#define SCOPE_GUARD_CONCATENATE(s1, s2) SCOPE_GUARD_CONCATENATE_IMPL(s1, s2)
#ifdef __COUNTER__
# define SCOPE_GUARD_ANONYMOUS_VARIABLE(str) SCOPE_GUARD_CONCATENATE(str, __COUNTER__)
#else
# define SCOPE_GUARD_ANONYMOUS_VARIABLE(str) SCOPE_GUARD_CONCATENATE(str, __LINE__)
#endif
#define SCOPE_EXIT auto SCOPE_GUARD_ANONYMOUS_VARIABLE(SCOPE_EXIT_STATE) = ::detail::ScopeGuardOnExit() + [&]()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment