0

这个问题是这个问题的后续问题:原始问题

我有一个继承自的类,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.
}
4

2 回答 2

2

你不能。那时,指向shared_ptr当前Self实例的 尚不存在。在构造函数返回之前,它不可能存在。shared_from_this()有一个前提条件,即 ashared_ptr已经存在,指向this.

于 2017-01-16T19:31:47.597 回答
1

你不能因为你必须是一个std::shared_ptr指向当前对象的存在。正如 Scott Meyers 在 Effective Modern C++(第 19 章)中所说,您可以将构造函数声明为私有,并使工厂函数返回 a 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();
}
于 2017-01-16T19:45:22.880 回答