Boost logo

Boost :

Subject: Re: [boost] [interest] rich-typed smart pointers
From: Gavin Lambert (gavinl_at_[hidden])
Date: 2013-10-06 20:34:25


On 10/6/2013 8:34 AM, Quoth Julian Gonggrijp:
> As for safety, I think std::weak_ptr is not really safer that rtp::weak_ptr
> because it's just as easy to produce a dangling pointer (in fact std takes
> only 3 lines of code to do it while rtp requires 4) and that's a disaster no
> matter what. The fact that it can detect that it's dangling does however
> make it easier to debug.

I fail to see why "dangling pointers" are a disaster with std::weak_ptr.

Their implementation does not permit any access without locking the
pointer, which will either succeed (and consequently prevent the object
from being destroyed while it is being accessed) or fail (if the object
has already been destroyed) and return a null pointer.

The code using the pointer has to be able to cope gracefully with
failure to obtain a pointer, but this is built into the semantics of
weak_ptrs -- if you can't write the code such that it can fail
gracefully, then you should have been using a shared_ptr instead so that
you can guarantee that the object won't disappear before you're ready
for it to do so.

Bare pointers, on the other hand (including rtp::weak_ptr, from what I
understand from this discussion, though I haven't examined the code
specifically) have no such tracking/locking capability so there is no
way to ensure that a particular pointer value still points at the same
object as it originally did.

Sure, it's still possible to get a null pointer access with
std::weak_ptr, by locking one and then accessing the resulting
shared_ptr without checking for validity (ie. lazy programmer). But in
this case it will assert, and even failing that null accesses are far
easier to track down and deal with than non-null-invalid-object accesses.

(I'm not saying that shared_ptrs don't have problems -- for example it's
far too easy to get into trouble with cyclic references if you're not
careful, and I've yet to find any good tools to track these down. But
they don't have *this* particular problem, since solving that is pretty
much their entire reason for existing in the first place.)


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