Boost logo

Boost :

Subject: Re: [boost] [Block Pointer] Question about cycles rationale
From: Gavin Lambert (gavinl_at_[hidden])
Date: 2016-03-14 21:01:36


On 15/03/2016 01:23, Phil Bouchard wrote:
> On 03/14/2016 07:35 AM, Rob Stewart wrote:
>>
>> Neither answer is great. The exception could occur during shack
>> unwinding, so you couldn't use your pointers in very many contexts. No
>> exception means UB, which means users have to remember a special case
>> and thereby lose safety.
>>
>> I fail to see how that is better than using weak_ptr. In that case,
>> one must always be explicit rather than remember special cases.
>
> It is much more complicated to use an explicit weak_ptr because you need
> to know where the cycle ends, etc.
>
> What if you have a neural network? How do you define where to use
> weak_ptr over shared_ptr, etc.?

The basic rule for tree structures is to use shared_ptr when pointing
"down" from parent to child and weak_ptr when pointing "up" from child
to parent.

(The above assumes that you want the whole tree to stay alive when you
have a pointer to the root, which is the common case. In some cases
though it's more useful to reverse the tree, such that keeping a pointer
to a child keeps all its parents alive. Either way works, though not
mixing the two.)

For more free-form graphs it's a bit harder to define, obviously. A
simple solution (albeit one that requires a bit of double handling) is
to have each node only use weak_ptrs to point at each other, and store
the shared_ptrs for each node in a bag or map in the graph container
object. It's typically only a slight increase in housekeeping work when
adding/removing nodes.


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