调用“shared_from_this”时错误的weak_ptr

Que*_*est 0 c++ shared-ptr

我组建了一个小类,继承自std::enable_shared_form_this如下:

class Foo : std::enable_shared_from_this<Foo>
{
    Foo() = default();
public:
    [[nodiscard]] static auto getInstance()
    {
        static auto f = std::shared_ptr<Foo>(new Foo());
        return f;
    }

    stream construct()
    {
        return stream{ shared_from_this() };
    }
};
Run Code Online (Sandbox Code Playgroud)

每当我打电话时construct()bad_weak_ptr exception都会被抛出。谁能解释为什么我会观察到这种行为?

编译:Apple clang 版本 13.0.0 (clang-1300.0.29.30)
目标:arm64-apple-darwin21.5.0

Sla*_*ica 6

如文档中所述(重点是我的)

从 std::enable_shared_from_this公开继承为类型 T 提供了一个成员函数shared_from_this。如果类型 T 的对象 t 由名为 pt 的 std::shared_ptr 管理,则调用 T::shared_from_this 将返回一个与 pt 共享 t 所有权的新 std::shared_ptr。

你的遗产是私人的,所以你违反了合同。

只需公开继承即可:

 class Foo : public std::enable_shared_from_this<Foo>
Run Code Online (Sandbox Code Playgroud)

  • @Quest:这是所有实现细节,但在大多数情况下,shared_ptr 构造函数会检查传入的对象是否继承自enable_shared_from_this。检查该继承要求它既是公共的又是明确的,否则底层检查将失败,并且会走另一条路。 (2认同)