Boost logo

Boost :

From: hicks (hicks_at_[hidden])
Date: 2002-05-15 19:54:00


Hi Peter,

you wrote

/Consider this example:
/weak_ptr<T> wp;
/
/// ...
/
/if(wp.get() != 0)
/{
/ wp->f();
/ wp->g();
/}

and also

/Looks innocent enough, but wp->f() may invalidate wp (by resetting the
/shared_ptr holding the object), and wp->g() will crash.
/The intended use pattern is for clients to take ownership only
temporary, as
/if holding a lock on the object; clearly, the object shouldn't go away in
/the middle of a "transaction."

If the design is such that wp may be invalidated in f(),
then it should be up to the user to decide whether wp->g()
should cause an error, or processing should continue.
The implications of silently continuing (as is posiible with a temporary
smart pointer) may be worse than a
pointer access violation. You can't say a priori.
The code can be simply fixed by writing
if(wp.get() != 0)
{
wp->f();
if (wp.get()) wp->g();
else (...)
}
which actually does a lot more to make clear what is going on in that
application
than forcing heavy policy on the user.

As for any argument which included multithreading, there is no good reason
force all coding to comply with MT "just in case". What is needed is to
clearly deliniate between the cases.

Craig Hicks


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