MGE | 7 Sep 03:44

newbie question on cyclic shared pointers


Hi guys, 

I have a data structure containing cycles of boost::shared_ptrs. I
understand that this is not advisable since the cycles may not be deleted
when shared pointers go out of scope. Possible solutions include the use of
weak_ptrs or, alternatively, manually removing the cycles before deletion of
pointers.

I am finding it difficult to use weak_ptrs because I cannot guarantee that
the single shared_ptr will outlive the numerous weak_ptrs. 

So I am trying to manually break the cycle at deletion. I would be grateful
if somebody could take a look at the code below, which illustrates my basic
approach. Assuming that I stringently break all cycles when a Child class or
Parent class goes out of scope, would this approach avoid memory leaks?
Would it be possible to put code into the destructor of Parent and Child
classes that automatically sets the shared pointer owned by the class to
null (not using the reset() function but by using the method below) hence
guaranteeing that cycles are broken at deletion?

Thanks for any advice!

Best regards,

MGE

---------------------

struct Child;
(Continue reading)

Scott McMurray | 7 Sep 06:06

Re: newbie question on cyclic shared pointers

On Sat, Sep 6, 2008 at 21:48, MGE <mick.elliot <at> gmail.com> wrote:
>
> So I am trying to manually break the cycle at deletion. I would be grateful
> if somebody could take a look at the code below, which illustrates my basic
> approach. Assuming that I stringently break all cycles when a Child class or
> Parent class goes out of scope, would this approach avoid memory leaks?
> Would it be possible to put code into the destructor of Parent and Child
> classes that automatically sets the shared pointer owned by the class to
> null (not using the reset() function but by using the method below) hence
> guaranteeing that cycles are broken at deletion?
>

You probably don't want to assign them to a new shared_ptr, since the
allocation is spurious.

This is sufficient in the example:

   // later, manually break the cycle
   child->myParent.reset();

In your real case, you may need to reset others, of course.

HTH,
~ Scott

Gmane