Skip to content

Instantly share code, notes, and snippets.

@tyhenry
Last active February 5, 2020 04:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tyhenry/8676d433a79bdab34c65476fd939afdc to your computer and use it in GitHub Desktop.
Save tyhenry/8676d433a79bdab34c65476fd939afdc to your computer and use it in GitHub Desktop.
RAII - auto-cleanup based on object lifetime
#include <iostream>
#include "raii.h"
int main() {
int value = 0;
std::cout << value << std::endl;
// scope_guard c'tor arg is run on scope_guard destruction
raii::scope_guard g(
[&](){
value = 0;
std::cout << value << std::endl;
} );
value = 6;
std::cout << value << std::endl;
}
#include <functional>
namespace raii {
struct scope_guard {
scope_guard(const std::function<void()>& f) : _f(f) {}
~scope_guard() { if (_f) _f(); }
protected:
std::function<void()> _f;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment