Boost logo

Boost :

Subject: Re: [boost] [interest] rich-typed smart pointers
From: Larry Evans (cppljevans_at_[hidden])
Date: 2013-10-07 09:54:26


On 10/07/13 08:34, Julian Gonggrijp wrote:
> Jonathan Wakely wrote:
>
>> On 7 October 2013 11:01, Julian Gonggrijp wrote:
>>>
>>> The std::weak_ptr detects the dangling pointer and changes it into a
>>> null pointer. This makes sense, because null pointers are easier to
>>> detect. However, as the surrounding code probably relies on a live
>>> pointer (because dangling pointers are never planned) the program is
>>> still going to fail. This is what I meant by "disaster".
>>
>> Why is it going to fail? Expired pointers (not dangling ones) most
>> certainly are planned, and weak_ptr is designed to support (and
>> detect) that case. Users of std::weak_ptr know that it needs to be
>> checked, and the explicit conversion that is needed makes it hard to
>> forget to do that. Either you say:
>>
>> std::shared_ptr<X> sp(wp);
>>
>> which will throw if weak_ptr.expired() is true, or you use the
>> non-throwing form in a conditional:
>>
>> if (auto sp = wp.lock())
>> /* ... */ ;
>> else
>> /* deal with it */ ;
>
> Of course a programmer can avoid the problem by doing the right thing.
> That's not what my paragraph above was about. As I stated in the
> follow-up, the same reasoning applies to the rtp pointers.
>
> Your own quick example clearly suggests how the programmer may do the
> wrong thing:
>
> auto sp = wp.lock();
> // use without checking for null
>

However, the key point, I believe, is that the programmer
*can* check for an expired weak_ptr with std::pointer.
OTOH, with rtp::weak_ptr (or whatever future name
you choose), the programmer has no such ability.

> Please note that I'm not disputing that reference counting has a clear
> advantage to single ownership in cases like these. I'm just saying
> that dangling or expired pointers can still be a pitfall despite that
> advantage.
>

I see your point. the rtp pointer has the advantage of much less
overyhead, but the disadvantage of makeing it harder to detect
dangling pointers and program a workaround.

Is that a good summary?

-regards,
Larry


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