【发布时间】:2017-12-29 08:20:55
【问题描述】:
我有一对我似乎无法避免循环包含问题的类:
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...
}
我知道共享指针和弱指针存在于对偶中以防止循环所有权,但是在指针是成员变量的情况下(即必须在标头而不是实现文件中定义),我如何才能利用没有循环包含的对偶?
【问题讨论】:
-
转发 - 声明一个类 (
class Foo;) 而不是在其中一个文件中包含标题? -
class GroupOfPoints; class Point { std::vector<std::weak_ptr<GroupOfPoints>> _groups; }; -
啊,我没有意识到可以通过类来做到这一点。我只熟悉函数的前向声明
-
"我了解共享指针和弱指针存在于对偶中以防止循环所有权" 不。错。正确的设计可以防止循环所有权
标签: c++ pointers smart-pointers circular-dependency