boost :: shared_ptr循环依赖

Tho*_*ten 3 c++ tree include shared-ptr

我有一个问题,我在每个级别使用不同的类实现了一个树.指向树项的指针是boost :: shared_ptr <>.

因为每个级别存储指向父级的指针和指向其子级的指针,所以在头文件中存在循环依赖关系.

代码如下所示:

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

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

};
Run Code Online (Sandbox Code Playgroud)

因为我使用boost :: shared_ptr我不能在B.hhp中使用前向声明.但我不知道如何解决这个问题.如果你可以帮助我会很好.

And*_*owl 5

因为我使用boost :: shared_ptr我不能在B.hhp中使用前向声明

这不是真的.声明a shared_ptr<>不应该要求指向类型完成:

#include <boost/shared_ptr.hpp>

class A;

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

class A { };
Run Code Online (Sandbox Code Playgroud)

您的问题不在于对头文件的相互依赖.你绝对可以使用前向声明来打破这些依赖.

您遇到的问题是在彼此保持活动的对象之间进行循环引用.要打破这个循环,请使用boost::weak_ptr.

此外,C++ 11引入了标准类模板std::shared_ptrstd::weak_ptr(在<memory>标题中定义),因此除非您使用C++ 03,否则您应该考虑使用这些类模板而不是Boost的模板.

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

//B.hpp
class B{
   boost::weak_ptr<A> parent;
};
Run Code Online (Sandbox Code Playgroud)