Last active
December 12, 2015 03:28
-
-
Save id-0x76adf1/4707060 to your computer and use it in GitHub Desktop.
scope guard
This file contains hidden or 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
| // from http://mindhacks.cn/2012/08/27/modern-cpp-practices/ | |
| #ifndef SCOPE_GUARD_H | |
| #define SCOPE_GUARD_H | |
| #include <functional> | |
| class scope_guard { | |
| private: | |
| scope_guard(const scope_guard&); | |
| scope_guard& operator=(const scope_guard&); | |
| public: | |
| scope_guard(std::function<void ()> on_exit_scope) | |
| : on_exit_scope_(on_exit_scope) | |
| , dismissed_(false) {} | |
| ~scope_guard() { | |
| if (!dismissed_) { | |
| on_exit_scope_(); | |
| } | |
| } | |
| void dismiss() { | |
| dismissed_ = true; | |
| } | |
| private: | |
| std::function<void ()> on_exit_scope_; | |
| bool dismissed_; | |
| }; | |
| #define SCOPEGUARD_LINENAME_CAT(name, line) name##line | |
| #define SCOPEGUARD_LINENMAE(name, line) SCOPEGUARD_LINENAME_CAT(name, line) | |
| #define ON_SCOPE_EXIT(callback) scope_guard SCOPEGUARD_LINENMAE(exit, __LINE__)(callback) | |
| #endif // SCOPE_GUARD_H |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment