Skip to content

Instantly share code, notes, and snippets.

@mgrabovsky
Last active July 30, 2016 12:25
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 mgrabovsky/1808014 to your computer and use it in GitHub Desktop.
Save mgrabovsky/1808014 to your computer and use it in GitHub Desktop.
Scoped temporary variable in C++
// http://stackoverflow.com/a/2553109/227159
/**
* In its constructor temp_value stores a reference to a variable and a copy of the
* variable's original value. In its destructor it restores the referenced variable
* to its original value. So, no matter what you did to the variable between
* construction and destruction, it will be reset when the temp_value object goes out
* of scope.
*/
template < class T >
class temp_value {
public :
temp_value(T& var) : _var(var), _original(var) {}
~temp_value() { _var = _original; }
private :
T& _var;
T _original;
temp_value(const temp_value&);
temp_value& operator=(const temp_value&);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment