我组建了一个小类,继承自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
如文档中所述(重点是我的)
从 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)
| 归档时间: |
|
| 查看次数: |
113 次 |
| 最近记录: |