Skip to content

Instantly share code, notes, and snippets.

@rbock
Created July 9, 2017 07:34
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 rbock/001552b574356b83c8cda8a6ff16efde to your computer and use it in GitHub Desktop.
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
#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