2017-01-16 36 views
0

這個問題是在這裏這個問題的跟進問題:original question自含的本身的shared_ptr是從的std ::繼承enable_shared_from_this

我有一個從std::enable_shared_from_this繼承的類和這個類包含一個std::shared_ptr<Self>

在我知道該課程的詳細信息已完成併成功後,在此課程的任何構造函數中,如何將存儲的std::shared_ptr<Self>分配爲shared this

例子:

class Self : public std::enable_shared_from_this<Self> { 
private: 
    std::shared_ptr<Self> me_; // Or 
    std::unique_ptr>Self> me_; 

public: 
    Self (/*some parameters*/); 
}; 

Self::Self(/* some parameters */) { 
    // Check parameters for creation 

    // Some work or initialization being done 

    // If all is successful and construction of this class is about 
    // to leave scope, then set the smart pointer to the this* 

    // How to do ... 
    me_ = std::enable_shared_from_this<Self>::shared_from_this(); 
    // Properly if this is even possible at all. 
} 
+0

@ Jason R哦,好吧。因此,它會要求我有一個包含它們實例的「管理器類型類」,或者我需要將它設置在函數中,以便在其構造函數(如構造函數或初始化函數)之後立即調用它。 –

+0

對自己的shared_ptr是一個矛盾。僅用於暫時保持對象存活(例如,在等待回調時)。 –

回答

2

你不能。此時,指向當前Self實例的shared_ptr還不存在。直到構造函數返回後纔可能存在。 shared_from_this()有一個先決條件,shared_ptr已經存在,指向this

+0

好吧,這是有道理的。所以我要麼需要一個包含共享指針的管理器類,要麼在這個類中有一個方法需要在構造函數之後調用,例如create()或init()方法。 –

+0

是的,沒錯。 –

+0

是的,從圖書館的這個部分繼承對我來說是新的。 –

1

您不能這樣做,因爲您必須是指向當前對象的現有std::shared_ptr。正如斯科特邁爾斯在有效的Modern C說++(第19章),你可以宣佈你的構造函數私有,並進行工廠函數返回一個std::shared_ptr,如:

class Self: public std::enable_shared_from_this<Self> { 
public: 
// factory function that perfect-forwards args 
// to a private ctor 
    template<typename... Ts> 
    static std::shared_ptr<Self> create(Ts&&... params); 
    ... 
    void process(); 
    ... 
private: 
    ... // ctors 
}; 

然後調用process,這可能是這樣的:

void Self::process() 
{ 
    ... 
    me_ = shared_from_this(); 
} 
+0

我認爲這在技術上是可行的(雖然可能是一個糟糕的設計)。看到我的評論JasonR的[答案](http://stackoverflow.com/a/41683759/3246555)。 – AlexD