2014-02-25 28 views
1

我有兩個類型:A & B. A「巧妙」點B和B「巧妙」點A. 在主範圍我有一個智能指針到A.C++智能指針圓形鏈路

class A; 
class B; 
typedef shared_ptr<A> pA; 
typedef shared_ptr<B> pB; 

class B { 
public: 
    B() {} 
    pA a; 
    virtual ~B() {cout << "delete b" << endl;} 
}; 

class A { 
public: 
    A() : b(new B()) {} 
    pB b; 
    virtual ~A() {cout << "delete a" << endl;} 
}; 

int main(int argc, char **argv) 
{ 
    { 
     pA pa(new A()); 
     pa->b->a = pa; 
    } 
    cout << "here" << endl; 

} 

我希望兩個對象在範圍的末尾被刪除。 沒有一個對象被刪除,因爲A有兩個指向自己的指針(一個在b中,另一個在主要的勺子中)。 enter image description here

這是一個簡單的例子。其實我有兩種以上的類型和更多的指針。 可以想象,一個大對象結構指向彼此漂浮在RAM中,只有一個指針指向主結構。這個指針被釋放後,我希望這個結構被刪除。

+0

好的圖紙的循環引用,爽! –

+0

相關:http://stackoverflow.com/questions/701456/what-are-potential-dangers-when-using-boostshared-ptr –

回答

6

對於可能出現循環依賴但重構架構的地方,最好使用weak_ptr以及shared_ptr

struct A { 
    std::shared_ptr<B> b; 
}; 

struct B { 
    std::weak_ptr<A> a; 

}; 
6

使用weak pointer某處打破循環 - 它的設計正是這種情況。

此外,std::weak_ptr是用來打破std::shared_ptr