c++ - 为什么我在使用enable_shared_from_this()时会遇到异常?

标签 c++ c++11 std

在下面的示例中,有些东西让我无法理解。如果存在对调用它的对象的未完成的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/

相关文章:

c++ - QT中如何将变量从一个线程共享到多个线程

c++ - 重载数组中的new和delete

c++ - 迭代不同的类型

c++ - std::bind 到局部变量作为值

c++ - qtextedit - 调整大小以适应

c++ - 加密++库中的SHA512哈希抛出异常

linux - Fedora 28/GLIBC 2.27 libm.so.6 logf() 和 powf() c++

c++ - 移动构造函数应该采用 const 还是非 const 右值引用?

c++ - std::max_element 跳过 NAN

c++ - 为什么 `std::conj(double d)` 不返回 `double` 而是返回 `std::complex<double>` ?