Skip to content

Instantly share code, notes, and snippets.

@a-bronx
Last active November 26, 2015 21:54
Show Gist options
  • Select an option

  • Save a-bronx/cd4174999165b1b7031a to your computer and use it in GitHub Desktop.

Select an option

Save a-bronx/cd4174999165b1b7031a to your computer and use it in GitHub Desktop.
//-------------------------------------------------------------------
// 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