在下面的示例中,有些东西让我无法理解。如果存在对调用它的对象的未完成的shared_ptr引用,为什么在使用shared_from_this时会生成通常的weak_ptr异常?
class A : std::enable_shared_from_this<A> {
public:
static std::shared_ptr<A> create() {
return std::shared_ptr<A>(new A());
}
A() {}
void setParent(const std::shared_ptr<A>& other) {}
std::shared_ptr<A> keep() {
auto o = A::create();
o->setParent(shared_from_this());
return o;
}
};
int main() {
std::shared_ptr<A> a = A::create();
auto s = a->keep();
}
最佳答案
您需要从 enable_shared_from_this
公开继承,以便共享 ptr ctor 可以看到它。
顺便说一句,clang 因此无法编译您的示例。
关于c++ - 为什么我在使用enable_shared_from_this()时会遇到异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53233296/