Boost logo

Boost :

From: Joseph Gottman (joegottman_at_[hidden])
Date: 2000-02-03 20:08:34


----- Original Message -----

> I have in mind a small (pretty??) class, which seems to me to be a yet
> another candidate to our boost utility library. I've seen it to be
> reinvented at least 2 times after I'd invented it myself , so I will be
not
> much surprised if someone say 'I have this one too'..
> And even if you didn't, but you had ever written a code which assign some
> temporary value to a variable at some place in a block (usually at the
> beginning), and restore the old value at the end of it, I am sure you
would
> appreciate this class :). It does exactly such thing - assign a new value
to
> a variable, storing the old one within itself, and restore the original
> value in its destructor.
> So the class itself:
>
> namespace boost {
> template<class T>
> class temp_value
> {
> public:
> typedef T value_type;
> temp_value( T* object_ptr, const T& new_value )
> : object_ptr_( object_ptr )
> , old_value_( *object_ptr ) { *object_ptr_ = new_value; }
>
> ~temp_value() { *object_ptr_ = old_value_; }
>
> private:
> T old_value_;
> T* object_ptr_;
> };
> }
>
> (Dave, I know, it must be renamed to 'temporary_value' =), and I agree
with
> you, unless we choose a totally different name.)
> And a typical usage (and test) may look like this:
>
> void temp_value_test() {
> bool flag = true;
> int count = 15;
> if ( flag ) {
> boost::temp_value<bool> tmp( &flag, false );
> assert( !flag );
> if ( !flag ) {
> boost::temp_value<int> tmp( &count, 0 );
> assert( !count );
> }
> assert( count == 15 );
> }
> assert( flag );
> }
>
> Any thoughts about it?
>
> -Alexy
>
Two comments:

     1) How about making the obi_ptr pointer a reference instead? Whenever
there is a pointer in a class and it isn't tested for null I get very
nervous, and it isn't very clear what should happen if a null pointer is
passed to the constructor.

     2) A static utility function like make_pair would be very useful.


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