Boost logo

Boost :

From: Martin Schürch (mschuerch_at_[hidden])
Date: 2000-11-14 11:22:01


Hi
I have looked at the implementation off auto_restore<>.
I don't know what was disussed about this before. But perhaps this was
not mentioned yet:
After reading the article "Generic<Programming>: Change the Way You
Write Exception -Safe Code Forever" of Andrei Alexandrescu, I
implemented auto_restore with the trick, where a reference to a
temporary instance is stored.

This would have the big advantage, that no type must be explicitely
delivered to create an auto_restorer .

Thanks for any feedback.
Martin

namespace boost{
   namespace helper {

      class auto_restore_base {
      public:
         ~auto_restore_base () {}
      private:
         auto_restore_base& operator=(const auto_restore_base&);
      };

      template <class T>
      class auto_restore_t : public auto_restore_base {
      public:
         auto_restore_t(T& variable)
            : variable_(variable), value_(variable) {}
         auto_restore_t(T& variable, const T& value)
            : variable_(variable), value_(value) {}
         ~auto_restore_t() { variable_ = value_;} //nicht virtual
      private:
         T& variable_;
         T value_;
      };
   } // helper

   typedef const helper::auto_restore_base& auto_restorer;

   template<class T>
   helper::auto_restore_t<T> make_restorer(T& variable, const T& val)
   {
      return helper::auto_restore_t<T>(variable, val);
   }

   template<class T>
   helper::auto_restore_t<T> make_restorer(T& variable)
   {
      return helper::auto_restore_t<T>(variable, variable);
   }
} // boost

#include <cassert>
#include <iostream>
using namespace std;

int main()
{
   {
      int value = 0;
      {
         boost::auto_restorer restorer = boost::make_restorer(value,
10);
         assert(value==0);
         value = 19;
         assert(value==19);
      }
      assert(value == 10);
   }

   {
      int value = 27;
      {
         boost::auto_restorer restorer = boost::make_restorer(value);
         assert(value==27);
         value = 19;
         assert(value==19);
      }
      assert(value == 27);
   }

   return 0;
}


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk