c++ - 自包含从 std::enable_shared_from_this 继承的自身的 shared_ptr

标签 c++ inheritance smart-pointers this-pointer

这个问题是这里问题的后续问题:original question

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

最佳答案

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

关于c++ - 自包含从 std::enable_shared_from_this 继承的自身的 shared_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41683709/

相关文章:

c++ - 激活在 R 中运行 libLAS C++ 库

c++ - 在源文件中内联

mysql - 如何在 Doctrine 中将鉴别器列定义为类表继承的 ENUM?

c# - WCF - 如何从基类型向客户端公开强类型对象(无需客户端转换?)

C++ intrusive_ptr 问题

c++ - 将 vector 成员变量返回给外部类的最佳方法

c++ - 对象的大小是否受访问说明符类型和继承类型的影响?

angularjs - 通过 $controller 从基本 Controller 继承的单元测试 AngularJS Controller

c++ - 引用已删除的函数数组

C++旧时间到现在的时间(以小时为单位)