我在使用 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/