我在使用shared_ptr
和weak_ptr
以及enable_shared_from_this
时遇到了问题。
当我搜索我看到的症状时,每个人都建议“当没有shared_ptr
实例拥有您的对象时,您不能使用shared_from_this()
。
但这不是我的情况。
考虑以下代码:
#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::shared_ptr
构造函数没有机制可以告诉你是否通过私有继承std::enable_shared_from_this
发生了错误,还是仅通过某个公开继承std::enable_shared_from_this
的类进行了私有继承。shared_from_this
函数无法知道最派生类类型,因此也无法检测程序员的错误。 - Brian Bistd::is_base_of
检查基类,如果它是模糊的或不可访问的,则进行投诉。 - Deduplicatorstd::enable_shared_from_this
派生,但只有在这样做时才会发生某些事情。这非常不好,并且如果您分配了另一个使用成员而不是继承的类,则无法正常工作。最好拥有自己的weak_ptr
并自行维护它。 - curiousguy