Boost logo

Boost :

From: Andy Little (andy_at_[hidden])
Date: 2006-02-12 12:07:51


"Reece Dunn" wrote

> what happens if you have a class called shared_data that uses shmem, and use
> it like this:
>
> shared_data data;
>
> int main()
> {
> return 0;
> }
>
> If this throws an exception, your application will crash and it could be
> difficult to determine why.

The other alternative is that you construct the object, its in a bad state but
because you made the darn thing a global variable you forget to check the state
before use, your application crashes or just hangs in an endless loop. I dont
know an answer except to change the design. The global object without
exceptions means less argument passing into functions but more tedious and error
prone checking of state within each function that references it. The current
practise in C++ design is create objects when you want them isnt it? Changing
the above design is a question of changing to

int main()
{
    try{
         shared_data data;
         use(data); // data guaranteed to be in a good state on entry

        // if here data still good
        ...
    }
    catch(shmem_exception & e){
            std::cout << "shmem failed\n";
            return Error;
    }
}

Are there particular situations where a design cant be modified to not use
global data? FWIW none of the shmem examples use global variables, though they
could do as currently designed. OTOH I believe std::basic_ostream and istream
handle the situation by means of "sentries" in their associated functions.[
C++PL 3rd Ed 21.3.8 ]. though in that example flags are set which user must
check. My preferred option is that (if possible!) a user of data in the above
example is guaranteed that s/he is either getting an object in a good state or
an exception has been thrown and doesnt need to remember to check the state at
hir end before each use. Of course if s/he can modify the state then we are back
in the same position, but again the policy should be that any user action that
is about to put the object in a bad state will rather throw an exception.

The kind of object that violently informs me its being put into a bad state is
preferable IMO to the one that silently continues. That said if there are
situation such as the no-exceptions platforms then the behaviour should be
suitably modified as a workaround only on those platforms otherwise we are just
denied using a well used language feature simply becaause its not universally
supported. AFAIK the practise of not allowing exceptions in e.g embedded use is
only unofficially supported isnt it?

regards
Andy Little


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