Boost logo

Boost :

From: Aleksey Gurtovoy (alexy_at_[hidden])
Date: 2000-02-15 07:35:12


Here it is. Or, rather, here they are ;) - 'scoped_value' and
'deffered_value' classes. The second one is an implementation of Dave's
'set_on_exit' class, but (as you see :) I gave it another name. Of course, a
need for this class and especially the name itself is a big discussion
point. But *I* feel both of them will be useful - each in its own way.

I've also uploaded the code to the vault to 'scoped_value' directory. So,
the code itself (without comments):

namespace boost {
namespace details {

template<class T>
class auto_restore
{
  protected:
    typedef auto_restore<T> inherited;

    auto_restore( T& variable, const T& value )
      : variable_( variable )
      , value_( value ) {}

    ~auto_restore() { variable_ = value_; }

  private:
    const T value_;
    T& variable_;
};
} // namespace details

template<class T>
class scoped_value
    : noncopyable
    , ::boost::details::auto_restore<T>
{
  public:
    typedef T value_type;

  public:
    scoped_value( T& variable, const T& new_value )
      : inherited( variable, variable ) { variable = new_value; }
};

template<class T>
class deffered_value
    : noncopyable
    , ::boost::details::auto_restore<T>
{
  public:
    typedef T value_type;

  public:
    deffered_value( T& variable, const T& future_value )
      : inherited( variable, future_value ) {}
};
} // namespace boost

And a very simple test/usage example:

int
main() {
  bool flag = true;
  int count = 15;
  long lock_count = 1;

  if ( flag ) {
    boost::scoped_value<bool> flag_in_scope( flag, false );

    assert( !flag );
    if ( !flag ){
      boost::deffered_value<long> future_lock_count( lock_count, 0 );
      boost::scoped_value<int> count_in_scope( count, 0 );
      assert( lock_count == 1 );
      assert( !count );
      }
    assert( !lock_count );
    assert( count == 15 );
  }
  assert( flag );
  return 0;
}

Any comments?

-Alexy





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