Boost logo

Boost :

From: Jason Hise (chaos_at_[hidden])
Date: 2005-03-15 11:17:36


Sérgio Vale e Pace wrote:

>>>template < typename T >
>>>struct auto_set
>>>{
>>> T & var; T val;
>>> auto_set ( T & var, T val ) :
>>>
>>>
>>auto_set(T & var,T val = T()):
>>// allows one to just specify a variable to be auto-set back to its default
>>value also
>>
>>
>>> var ( var ), val ( val ) { }
>>>
>>>
>
>// IMHO I thing it´s more often useful to use var own value to be
>restored later:
>auto_set(T& var) : var(var), val(var) { }
>
>
>
>>> ~ auto_set ( ) { var = val; }
>>>};
>>>
>>>

Perhaps. You might be interested to see why I originally wrote it though:

virtual void create ( )
{
    if ( !s_inst && !creating )
    {
        creating = true;
        auto_set < bool > reset ( creating, false );
        s_inst = creator_inst.create ( );
    }
}

virtual void destroy ( )
{
    if ( s_inst && !destroying )
    {
        destroying = true;
        auto_set < bool > reset_d ( destroying, false );
        auto_set < raw_pointer > reset_p ( s_inst, 0 );
        creator_inst.destroy ( s_inst );
    }
}

Basically, when create is called, the constructor of the singleton being
created just might do something that would normally cause that singleton
to be automatically created. I use a bool to remember that a creation
is in progress, and auto_set makes sure that it gets turned off when the
scope is exited.

The same kind of thing is going on in destroy, but I also ensure that
the pointer to the singleton gets reset to null after destruction is
complete.

-Jason


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