Skip to content

Instantly share code, notes, and snippets.

@bisqwit
Last active August 29, 2015 14:01
Show Gist options
  • Save bisqwit/921a66e90631ab96c6be to your computer and use it in GitHub Desktop.
Save bisqwit/921a66e90631ab96c6be to your computer and use it in GitHub Desktop.
Scoped temporary values
/**
*
* Block-local temporaries
*
* Copyright (C) 2006,2014 Bisqwit (http://iki.fi/bisqwit/)
*
* Example use:
* bool in_critical_context = false;
*
* void example()
* {
* block_setting<bool> block_marker(in_critical_context, true);
* ...
* // in_critical_context will be automatically restored to
* // whatever it was at function entrance, when the scope is exited.
* }
*
* If you wanted to do this with the standard library's tools, you would have
* to do something like this:
*
* void example2()
* {
* std::unique_ptr<void,std::function<void(void*)>>
* block_marker(nullptr,
* [=](bool& v){bool o=v; v=true;
* return [=](void*){in_critical_context=o;};
* }(in_critical_context));
* ...
* }
*
* Or with hand-written (and always duplicated) code:
*
* void example3()
* {
* struct tmp { bool o; ~tmp(){ in_critical_context = o; } } tmp{in_critical_context};
* in_critical_context = true;
* ...
* }
}
**/
template<typename T>
class block_setting
{
T oldvalue;
T& var;
public:
block_setting(T& v, const T& tempval) : oldvalue(std::move(v)), var(v)
{
var = tempval;
}
~block_setting()
{
var = std::move(oldvalue);
}
block_setting& operator=(const block_setting&) = delete;
block_setting(const block_setting&) = delete;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment