fix doc example typo
[boost.git] / boost / serialization / state_saver.hpp
blob76bb4d6a50eaa312646fb72212f0b12e2c8cf5aa
1 #ifndef BOOST_SERIALIZATION_STATE_SAVER_HPP
2 #define BOOST_SERIALIZATION_STATE_SAVER_HPP
4 // MS compatible compilers support #pragma once
5 #if defined(_MSC_VER) && (_MSC_VER >= 1020)
6 # pragma once
7 #endif
9 /////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
10 // state_saver.hpp:
12 // (C) Copyright 2003-4 Pavel Vozenilek and Robert Ramey - http://www.rrsd.com.
13 // Use, modification and distribution is subject to the Boost Software
14 // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
15 // http://www.boost.org/LICENSE_1_0.txt)
17 // See http://www.boost.org/libs/serialization for updates, documentation, and revision history.
19 // Inspired by Daryle Walker's iostate_saver concept. This saves the original
20 // value of a variable when a state_saver is constructed and restores
21 // upon destruction. Useful for being sure that state is restored to
22 // variables upon exit from scope.
25 #include <boost/config.hpp>
26 #ifndef BOOST_NO_EXCEPTIONS
27 #include <exception>
28 #endif
30 #include <boost/call_traits.hpp>
31 #include <boost/noncopyable.hpp>
32 #include <boost/type_traits/has_nothrow_copy.hpp>
33 #include <boost/detail/no_exceptions_support.hpp>
35 #include <boost/mpl/eval_if.hpp>
36 #include <boost/mpl/identity.hpp>
38 namespace boost {
39 namespace serialization {
41 template<class T>
42 // T requirements:
43 // - POD or object semantic (cannot be reference, function, ...)
44 // - copy constructor
45 // - operator = (no-throw one preferred)
46 class state_saver : private boost::noncopyable
48 private:
49 const T previous_value;
50 T & previous_ref;
52 struct restore {
53 static void invoke(T & previous_ref, const T & previous_value){
54 previous_ref = previous_value; // won't throw
58 struct restore_with_exception {
59 static void invoke(T & previous_ref, const T & previous_value){
60 BOOST_TRY{
61 previous_ref = previous_value;
63 BOOST_CATCH(::std::exception &) {
64 // we must ignore it - we are in destructor
66 BOOST_CATCH_END
70 public:
71 state_saver(
72 T & object
73 ) :
74 previous_value(object),
75 previous_ref(object)
78 ~state_saver() {
79 #ifndef BOOST_NO_EXCEPTIONS
80 typedef BOOST_DEDUCED_TYPENAME mpl::eval_if<
81 has_nothrow_copy<T>,
82 mpl::identity<restore>,
83 mpl::identity<restore_with_exception>
84 >::type typex;
85 typex::invoke(previous_ref, previous_value);
86 #else
87 previous_ref = previous_value;
88 #endif
91 }; // state_saver<>
93 } // serialization
94 } // boost
96 #endif //BOOST_SERIALIZATION_STATE_SAVER_HPP