Last active
November 26, 2015 21:54
-
-
Save a-bronx/cd4174999165b1b7031a to your computer and use it in GitHub Desktop.
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
| //------------------------------------------------------------------- | |
| // Provides a "finally" lambda block for C++. | |
| // Example: | |
| // | |
| // void ReenterableFunction() { | |
| // static bool isActive = true; // static reenterability flag | |
| // | |
| // if (isActive) return; // check the flag | |
| // auto reset = finally([&]{ isActive = false; }); // we need to reset the flag on exit, even if there was an exception in the code below. | |
| // isActive = true; // set the flag and proceed | |
| // | |
| // // ... do your job here .. | |
| // | |
| // } // here the flag will be automatically reset | |
| // | |
| // | |
| template <typename F> | |
| struct finalizer | |
| { | |
| // move constructor | |
| template<typename T> | |
| finalizer(T&& finalize) : _finalize(std::forward<T>(finalize)), _armed(true) { | |
| } | |
| // old-style move constructor | |
| finalizer(finalizer&& other) : _finalize(std::move(other._finalize)), _armed(other._armed) { | |
| other.disarm(); | |
| } | |
| ~finalizer() { | |
| if (_armed) _finalize(); | |
| } | |
| void disarm() { | |
| _armed = false; | |
| } | |
| private: | |
| F _finalize; | |
| bool _armed; | |
| }; | |
| template <typename F> | |
| finalizer<F> finally(F&& finalize) { | |
| return finalizer<F>(std::forward<F>(finalize)); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment