Boost logo

Boost Users :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2003-06-11 12:27:17


Zumichu wrote:
>
> GraphNode
> {
> public:
> AddChild(shared_ptr<GraphNode> n)
> {
> m_Children.push_back(n);
> shared_ptr<GraphNode> thisptr(this);
> n->m_Parents.push_back(thisptr);
> }
>
> DeleteChild(shared_ptr<GraphNode> n);
>
> private:
> vector<shared_ptr<GraphNode> > m_Children;
> vector<shared_ptr<GraphNode> > m_Parents;
> };

There are two problems with your code. First,

shared_ptr<GraphNode> thisptr(this);

is wrong. A shared_ptr cannot be constructed from an arbitrary raw pointer.
Change AddChild to:

friend void AddChild(shared_ptr<GraphNode> this_, shared_ptr<GraphNode> n)
{
    this_->m_Children.push_back(n);
    n->m_Parents.push_back(this_);
}

Second, you will now have a cyclic reference where the child owns its
parents and the parent owns its children, and they'll keep each other alive,
creating a memory leak. Change m_Parents to

vector< weak_ptr<GraphNode> > m_Parents;

to prevent that from happening.

vector< GraphNode* > m_Parents;

combined with your original AddChild is possible, too, if you aren't afraid
of parents disappearing without notice.


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