gpt4 book ai didi

c++ - 对象构造后 shared_from_this 中的 std::bad_weak_ptr 异常

转载 作者:太空宇宙 更新时间:2023-11-04 15:00:05 26 4
gpt4 key购买 nike

我定义了一个类似于下面的类:

class A : std::enable_shared_from_this<A> {
public:
static std::shared_ptr<A> create() {
return std::shared_ptr<A>(new A());
}

void f() {
shared_from_this();
}

private:
A() { }
};

它的用法类似于:

std::shared_ptr<A> pt = A::create();
pt->f();

尽管在创建 shared_ptr pt 之后调用了 shared_from_this(),但调用 f() 仍然会导致 bad_weak_ptr 抛出异常。在 gdb 中运行它可以确认异常是在调用 f() 时抛出的,而不是在我未包含在此处的一些由讲师调用的代码中抛出的。

最佳答案

std::enable_shared_from_this<A>必须是公共(public) 基地。当 shared_ptr构造函数看到你从 enable_shared_from_this 派生, 它在 enable_shared_from_this 中存储了自身的弱拷贝目的。如果继承不是公共(public)的,则不会发生这种情况,并且 weak_ptr存储在 enable_shared_from_this 中将为空,导致 bad_weak_ptr shared_from_this 时异常后来尝试构建一个 shared_ptr从它。

关于c++ - 对象构造后 shared_from_this 中的 std::bad_weak_ptr 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52194823/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com