C++ Boost

Serialization

state_saver


Sometimes a certain value has to change only for a limited scope. This class wrapper saves a copy of the current state of some object, and resets the object's state at destruction time, undoing any change the object may have gone through. Here is the interface:


template
// T requirements:
//  - POD or object semantic (cannot be reference, function, ...)
//  - copy constructor
//  - operator = (no-throw one preferred)
class state_saver : private boost::noncopyable
{
private:
    ... // implementation

public:
    state_saver(T & object);
    ~state_saver();
};
The complete implementation can be found here The following illustrates how this is expected to be used.

#include <boost/state_saver.hpp>

void func(A & a)
    boost::state_saver<A> s(a);
    ... // alter state of a by calling non-const functions
    ... // call other functions
    // original state of a automatically restored on exit
}

History

This is a generalization of Daryle Walker's io_state_saver library.

Robert Ramey made an initial version for the serialization library.

Pavel Vozenilek made several non-obvious refinements to make it more secure and boost friendly


© Copyright Robert Ramey 2002-2004. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)