使用 shared_ptrs 避免循环包含

Avoiding circular includes with shared_ptrs

我有一对 类,我似乎无法避免循环包含问题:

point.h

#include group.h // Needed for GroupOfPoints::weak_ptr

class Point
{
    private:
        double _x;
        double _y;

        // Groups of points that this point belongs too
        std::vector<GroupOfPoints::weak_ptr> _groups;

    public:
        typedef std::shared_ptr<Point> shared_ptr;
        typedef std::weak_ptr<Point> weak_ptr;

        Point(); // Constructor
        // etc...
}

group.h

#include point.h // Needed for Point::shared_ptr

class GroupOfPoints
{

    private:
        // Collection of points that fall in this group
        std::vector<Point::shared_ptr> _points;

    public:
        typedef std::shared_ptr<GroupOfPoints> shared_ptr;
        typedef std::weak_ptr<GroupOfPoints> weak_ptr;

        GroupOfPoints(); // Constructor
        // etc...

}

我知道共享指针和弱指针存在于对偶性中以防止循环所有权,但是如果指针是成员变量(即必须在 header而不是实现文件)?

首先去掉这个:

typedef std::shared_ptr<Point> shared_ptr;
typedef std::weak_ptr<Point> weak_ptr;

我不明白这一点。

std::shared_ptr<Foo>Foo::shared_ptr.

更清楚

现在,向前声明 class Point;class Group;。这可以代替 #include <point.h>,或 before 包括其他头文件。

接下来确保你的构造函数定义的,在那里他们可以看到另一个class的完整声明;无论你在哪里调用 make_shared<Foo>new Foodelete Fooshared_ptr<Foo>(pFoo)。共享指针类型在构造时擦除销毁。