The question is pretty simple: On occasion I encounter situations in which I modify some (rather global) state, for example a log level — to preempt bitching about global states: Not my framework, nothing I can do about it ;-).
In order to be nice I should restore the old state after I'm done, so I save it and at the end restore it. This is an obvious case for RAII:
// Some header
/// A RAII class which records a state and restores it upon destruction.
struct StateRestorer
{
State oldState;
StateRestorer(State oldStateArg) : oldState(oldStateArg) {}
~StateRestorer() { setState(oldState); }
};
// Happens a couple times somewhere in my program
{
StateRestorer oldStateRestorer(getState());
State newState(/* whatever */);
setState(newState);
// Do actually useful things during the new state
// oldStateRestorer goes out of scope and restores the old state.
}
Now, I don't actually need the oldStateRestorer variable. Don't get me wrong, I do need the object it refers to; but I never access oldStateRestorer in any way. The need to have a name for it is mildly cumbersome. If I were alone I might call it s but I'm a strong proponent of good naming so that people to whom the program is unfamiliar (likely me in two years) can readily understand it. On occasion these state variations are nested so that I have to invent new names lest my compiler warns me that I'm shadowing another variable (which in other cases is a serious warning, and I don't like warnings to begin with and now I'm all upset). As I said, mildly annoying.
The question boils down to this:
Is there a way to have an unnamed object whose lifetime is a block of code in C++?
(If somebody felt compelled to give an example in their favorite different language I wouldn't mind though.)