Boost logo

Boost :

From: Emil Dotchevski (emil_at_[hidden])
Date: 2007-11-02 18:43:13


> >I am often asked why shared_ptr always uses the custom deleter even when
> > the pointer argument is zero. I know it is safe to delete a NULL pointer
> > so this works with delete but it would seem that if the user is giving a
> > custom deleter, then they are probably doing something else. ie
> >
> > //will crash if fread returns 0
> > shared_ptr<FILE> foo(fread("foo.txt","r"),fclose);
>
> Neither alternative is a clear winner. What tips the scales somewhat is that
> (a) typically an idiomatic C++ wrapper over FILE would not construct a
> shared_ptr when fopen fails, it will throw an exception, (b) many resource
> releasing functions (such as 'free') do ignore NULLs instead of crashing,
> and (c) there is a relatively easy (if inconvenient) workaround.

Somewhat related issue, if a shared_ptr returns "true" when used in
boolean contexts, it means get() would not return null and therefore
it is "safe" to dereference the pointer. On the other hand, sometimes
the user needs to know if the shared_ptr is empty, which currently can
only be done in a clumsy roundabout way.

I have also had use cases when I needed to check a weak_ptr for the
"empty" state, which also is not the same as indicated by expired().

-- 
Emil Dotchevski
Reverge Studios, Inc.
http://www.revergestudios.com/reblog/index.php?n=ReCode

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