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.
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;
};