2017-07-23 34 views
0

我有一對類包括I似乎對於不能避免圓形包括問題:避免圓形與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... 

} 

我知道共享和弱指針存在於雙重性中以防止循環所有權,但在指針是成員變量的情況下,我怎樣才能利用這種沒有循環的二元性?必須在頭文件而不是實現文件中定義)?

+1

向前聲明一個類('類Foo;')而不是在其中一個文件中包含頭文件? – HolyBlackCat

+3

'class GroupOfPoints; class Point {std :: vector > _groups; };' –

+1

您必須使用前向聲明[何時可以使用前向聲明?](https://stackoverflow.com/questions/553682/when-can-i-use-a-forward-declaration) – Rabbid76

回答

2

首先擺脫這樣的:

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>之前的包括其他頭文件。

下一頁確保您構造定義在那裏他們可以看到其他類的整個聲明;無論您撥打make_shared<Foo>還是new Foodelete Fooshared_ptr<Foo>(pFoo)。共享指針在構建時鍵入擦除銷燬。

+0

謝謝。 typedef的要點是因爲我之前使用了boost指針,並且當我不得不將所有代碼切換到C++ 11智能點時都會遇到這種習慣 - 誰知道:也許C++ 20將會有一些新的shared_ptr類型?並且構造函數將在cpp文件中定義或者在下面定義。它似乎沒有必要完全寫出來,以獲得我的觀點 – marcman

+1

@marc typedefs可以成爲該類型的別名* *。 – Yakk