Skip to content

Instantly share code, notes, and snippets.

@willir
Created June 2, 2015 07:45
Show Gist options
  • Save willir/bca0a7914ea8aeb89448 to your computer and use it in GitHub Desktop.
Save willir/bca0a7914ea8aeb89448 to your computer and use it in GitHub Desktop.
C++11 Scope Guard. I.e. Class which will run some lambda which is set in constructor.
//
// Created by willir on 6/2/15.
//
#ifndef QRCODEGEN_SCOPEGUARD_H
#define QRCODEGEN_SCOPEGUARD_H
#include <functional>
/**
* @brief The ScopeGuard class for run some code while exits outside scope.
*/
class ScopeGuard {
public:
/**
* @brief ScopeGuard
* @param fn Labmda which will be called in destructor
*/
ScopeGuard(const std::function<void()> &fn) : mFunc(fn) {}
ScopeGuard(std::function<void()> &&fn) : mFunc(std::move(fn)) {}
~ScopeGuard() {
if(mIsEnable) {
mFunc();
}
}
/**
* @brief disable Disables ScopeGuard. So labmda will not be called in destructor.
* By default it is enabled.
*/
void disable() { mIsEnable = false; }
void enable() { mIsEnable = true; }
bool isEnabled() { return mIsEnable; }
private:
std::function<void()> mFunc;
bool mIsEnable = true;
};
#endif //QRCODEGEN_SCOPEGUARD_H
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment