Skip to content

Instantly share code, notes, and snippets.

@id-0x76adf1
Last active December 12, 2015 03:28
Show Gist options
  • Select an option

  • Save id-0x76adf1/4707060 to your computer and use it in GitHub Desktop.

Select an option

Save id-0x76adf1/4707060 to your computer and use it in GitHub Desktop.
scope guard
// 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