Last active
July 30, 2016 12:25
-
-
Save mgrabovsky/1808014 to your computer and use it in GitHub Desktop.
Scoped temporary variable in C++
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
// 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