Lub*_*osD 32 c++ shared-ptr weak-ptr private-inheritance enable-shared-from-this
我在shared_ptr和weak_ptr一起使用时遇到了麻烦enable_shared_from_this。
当我用Google搜索所见事物的症状时,每个人都建议“ 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();
}
Run Code Online (Sandbox Code Playgroud)
两种方法都会MyClass使程序崩溃。我一定缺少明显的东西-这是什么?
Igo*_*nik 41
您必须公开继承自std::enable_shared_from_this。私有继承无济于事- std::shared_ptr无法访问基类并正确设置它。
| 归档时间: |
|
| 查看次数: |
1435 次 |
| 最近记录: |