Created
August 8, 2014 22:49
-
-
Save mmozeiko/b22f86d3fb08b544e839 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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