Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RAII object for restoring previous value

Tags:

c++

boost

c++03

Perhaps I'm over thinking this but consider the following example:

bool some_state = false;

// ... later ...

some_state = true;
do_something();
some_state = false;

Now imagine that do_something() can throw. We won't set some_state back to false. What would be nice is to have some sort of automatic stack that pushes/pops based on scope for remembering previous values:

{
    scoped_restore res( some_state, true ); // This sets some_state to true and remembers previous value (false)
    do_something();
} // At this point, res is destroyed and sets some_state back to false (previous value)

Does boost have something like this? I can write my own object of course but I want to make sure I'm not reinventing the wheel first. I'm using C++03 on MSVC, so I can't use any fancy new C++11 unfortunately :(

like image 497
void.pointer Avatar asked Jul 23 '13 23:07

void.pointer


1 Answers

Boost does have something like this. It's called state_saver. It's kind of buried in the serialization library, but it is documented and apparently official (i.e. not in some detail namespace).

http://www.boost.org/doc/libs/1_56_0/libs/serialization/doc/state_saver.html

Demo: http://rextester.com/NVXUG70771

like image 94
SCFrench Avatar answered Nov 02 '22 04:11

SCFrench