這個問題是在這裏這個問題的跟進問題: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.
}
@ Jason R哦,好吧。因此,它會要求我有一個包含它們實例的「管理器類型類」,或者我需要將它設置在函數中,以便在其構造函數(如構造函數或初始化函數)之後立即調用它。 –
對自己的shared_ptr是一個矛盾。僅用於暫時保持對象存活(例如,在等待回調時)。 –