Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost::shared_ptr circular dependency

I have a question, I implemented a tree using different classes at each level. The pointer to the tree items are boost::shared_ptr<>.

Because each level stores a pointer to the parent and a pointer to its children there is a circular dependency in the header files.

The code looks like this:

//A.hpp
class A
{
    List<boost::shared_ptr<B> > children;
};

//B.hpp
class B{
   boost::shared_ptr<A> parent;

};

Because I use boost::shared_ptr I cannot use forward declaration in B.hhp. But I don't know how to solve this problem. It would be nice if you could help me.

like image 745
Thorsten Avatar asked Jan 21 '26 20:01

Thorsten


1 Answers

Because I use boost::shared_ptr I cannot use forward declaration in B.hhp

This is not true. Declaring a shared_ptr<> should not require the pointed type to be complete:

#include <boost/shared_ptr.hpp>

class A;

int main()
{
    boost::shared_ptr<A> pA; // OK
}

class A { };

Your problem is not with mutual dependency on header files. You definitely can use forward-declarations to break those dependency.

The problem you are having is circular referencing between objects that keep each other alive. To break this cycle, use boost::weak_ptr.

Also, C++11 introduces the standard class templates std::shared_ptr and std::weak_ptr (defined in the <memory> header), so unless you're working with C++03, you should consider using these class templates instead of Boost's ones.

//A.hpp
class A
{
    List<boost::shared_ptr<B> > children;
};

//B.hpp
class B{
   boost::weak_ptr<A> parent;
};
like image 184
Andy Prowl Avatar answered Jan 24 '26 13:01

Andy Prowl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!