Created
July 9, 2017 07:34
-
-
Save rbock/001552b574356b83c8cda8a6ff16efde to your computer and use it in GitHub Desktop.
auto_recover: A class to that will restore the value of a variable on scope exit
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> | |
// --------------------------------------------- | |
template<typename T> | |
class auto_recover_t | |
{ | |
T& _ref; | |
T _value; | |
public: | |
auto_recover_t(T& ref): | |
_ref(ref), _value(ref) | |
{ | |
} | |
~auto_recover_t() | |
{ | |
_ref = _value; | |
} | |
}; | |
template<typename T> | |
auto auto_recover(T& ref) -> auto_recover_t<T> | |
{ | |
return {ref}; | |
} | |
// --------------------------------------------- | |
int status = 5; | |
void foo() | |
{ | |
const auto recover = auto_recover(status); | |
status = 3; | |
std::cout << "status in foo: " << status << std::endl; | |
} | |
int main() | |
{ | |
foo(); | |
std::cout << "status after returning from foo: " << status << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment