I'm having trouble using shared_ptr
and weak_ptr
along with enable_shared_from_this
.
When I google the symptoms of what I'm seeing, everybody suggests "you cannot use shared_from_this()
when there are no shared_ptr
instances owning your object.
But that's not my case.
Consider this code:
#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();
}
Both methods in MyClass
crash the program. I must be missing something obvious - what is it?