Boost logo

Boost Users :

Subject: [Boost-users] newbie question on cyclic shared pointers
From: MGE (mick.elliot_at_[hidden])
Date: 2008-09-06 21:48:08


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;

struct Parent
{
   boost::shared_ptr<Child> myChild;
};

struct Child
{
  boost::shared_ptr<Parent> myParent;
};

boost::shared_ptr<Child> child(new Child());
boost::shared_ptr<Parent> parent(new Parent());

// create a cycle of pointers

parent->myChild = child;
child->myParent = parent;

// do something
// ....

// later, manually break the cycle

parent->myChild = boost::shared_ptr<Child>(new Child());
child->myParent = boost::shared_ptr<Parent>(new Parent());

// there are no longer any cyclic pointers

// parent and child go out of scope here, hopefully releasing all memory?

-- 
View this message in context: http://www.nabble.com/newbie-question-on-cyclic-shared-pointers-tp19353536p19353536.html
Sent from the Boost - Users mailing list archive at Nabble.com.

Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net