c++ - shared_ptr 和 weak_ptr 失败的小例子

标签 c++ shared-ptr weak-ptr private-inheritance enable-shared-from-this

我在使用 shared_ptr 时遇到问题和 weak_ptr连同 enable_shared_from_this .

当我用谷歌搜索我所看到的症状时,每个人都建议“当没有 shared_from_this() 实例拥有你的对象时,你不能使用 shared_ptr

但这不是我的情况。

考虑这段代码:

#include <memory>
#include <cassert>

class MyClass : std::enable_shared_from_this<MyClass>
{
public:
    void this_fails()
    {
        // Doesn't even assert(), because it throws bad_weak_ptr
        assert(shared_from_this());
    }
    void this_fails_too()
    {
        std::weak_ptr<MyClass> weak = weak_from_this();
        std::shared_ptr<MyClass> strong = weak.lock();
        // This assert fails
        assert(strong.get());
    }
};

int main()
{
    std::shared_ptr<MyClass> obj = std::make_shared<MyClass>();

    obj->this_fails();
    obj->this_fails_too();
}

MyClass 中的两种方法使程序崩溃。我一定遗漏了一些明显的东西 - 它是什么?

最佳答案

您必须公开std::enable_shared_from_this 继承。私有(private)继承没有帮助 - std::shared_ptr 无法访问基类并正确设置它。

关于c++ - shared_ptr 和 weak_ptr 失败的小例子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57064277/

相关文章:

c++ - C++中与Arduino的串行通信超时

c++ - 无法将元素添加到共享指针的线程安全锁定队列中

c++ - weak-ptr 变为 null,应用程序每周崩溃 1 次

c++ - 具有成员函数指针的模板的默认值

c++ - 将 textBox 传递给函数。 C++

c++ - 使用 `gluUnProject` 在 opengl 中进行鼠标拾取

c++ - boost::shared_ptr 和分配派生类

c++ - 每帧在 shared_ptr 中动态分配图像

c++ - 在没有其他智能指针的情况下创建weak_ptr

c++ - 来自 enable_shared_from_this 的子类