2016-09-15 24 views
0

我有一個類A,它提供了構造類B的實例的方法。並且B擁有對A的私有引用,並提供了一個構造函數來設置此引用。C++中依賴類的生存期?

class A { 
    public: 
    B* construct_B(); 
} 
class B { 
    private: 
    const A& private_A; 
    public: 
    B (const A& my_A): private_A (my_A) { } 
} 

construct_B實現通過this負責動態分配的,並通過引用本身。

如何以確保A的使用期限長於B的方式實施此設置,以便其參考仍然有效?請注意,我並不關心construct_B的所有可能性,而不是返回一個原始指針,我可以返回一個智能指針或類似的指針。

解決這個可以有B,而不是拿着參照智能指針堅持A,而是動態分配在construct_BB採取靜態參考B,然後設置它的指針,類似的一個可能的方法

class A : 
    public std::enable_shared_from_this<A> { 
    public: 
     void setup_B (const B& my_B) { 
     my_B.set_A (shared_ptr_from_this()) ; 
} 
class B { 
    private: 
    const shared_ptr<A> private_A_ptr; 
    public: 
    void set_A (const shared_ptr<A> my_A): 
     private_A_ptr (my_A) { } 
} 

其然後可以通過 INT主(){ 甲static_A來實現; B static_B;A.setup_B(static_B); }

這最後一次施工的shared_ptr是否避免在B之前刪除A的問題?

+0

爲什麼你不試試它,並做一些控制檯輸出?但是,只有當沒有人指向A時,A纔會被刪除。 – Hayt

+1

「這最後一個構造的shared_ptr是否避免了在B之前被刪除的問題?唯一的警告是,A本身必須由shared_ptr擁有,否則shared_from_this()將是UB。 –

回答

2

shared_ptr是你的答案。像這樣:

#include <memory> 

struct A; 

class B { 
    const std::shared_ptr<A> private_A_ptr; 
    public: 
    B(std::shared_ptr<A> parent) : private_A_ptr(std::move(parent)) {} 
}; 

struct A : 
std::enable_shared_from_this<A> 
{ 
    B make_b() { 
    return B(shared_from_this()); 
    } 
}; 

int main() 
{ 
    // this would be invalid: 
    //A a; 
    //auto b = a.make_b(); 

    // but this is fine 

    auto pa = std::make_shared<A>(); 
    auto b = pa->make_b(); 

    // later... 
    pa.reset(); 

    // A still exists because ownership was shared with b 

}