Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #pragma once
- // https://www.youtube.com/watch?v=WjTrfoiB0MQ
- #include <utility>
- template<typename T>
- class ScopeGuard final
- {
- public:
- explicit ScopeGuard(T onExit)
- : ready_(true)
- , onExit_(onExit)
- {
- }
- ScopeGuard(ScopeGuard&& other) noexcept
- : ready_(true)
- , onExit_(other.onExit_)
- {
- other.ready_ = false;
- }
- ~ScopeGuard()
- {
- if (ready_)
- {
- onExit_();
- ready_ = false;
- }
- }
- ScopeGuard() = delete;
- ScopeGuard(ScopeGuard& other) = delete;
- ScopeGuard& operator=(ScopeGuard&& other) = delete;
- ScopeGuard& operator=(const ScopeGuard& other) = delete;
- private:
- bool ready_;
- T onExit_;
- };
- namespace detail
- {
- enum class ScopeGuardOnExit {};
- template<typename Function>
- ScopeGuard<Function> operator+(ScopeGuardOnExit, Function&& function)
- {
- return ScopeGuard<Function>(std::forward<Function>(function));
- }
- }
- #define CONCATENATE_IMPL(s1, s2) s1##s2
- #define CONCATENATE(s1, s2) CONCATENATE_IMPL(s1, s2)
- #ifdef __COUNTER__
- #define ANONYMOUS_VARIABLE(string) CONCATINATE(string, __COUNTER__)
- #else
- #define ANONYMOUS_VARIABLE(string) CONCATINATE(string, __LINE__)
- #endif
- #define SCOPE_EXIT auto ANONIMOUS_VARIABLE(SCOPE_EXIT_STATE) = ::detail::ScopeGuardOnExit + (&)[]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement