Last active
February 5, 2020 04:45
-
-
Save tyhenry/8676d433a79bdab34c65476fd939afdc to your computer and use it in GitHub Desktop.
RAII - auto-cleanup based on object lifetime
This file contains 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
#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; | |
} |
This file contains 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
#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