This online reference for bad_weak_ptr
tells us that the exception is thrown when you try to create a shared_ptr
from a weak_ptr
that has already been deleting.
That's generally an odd thing to do, so if at all possible don't do that.
The better pattern is to call the lock method on the weak pointer, which returns a shared_ptr
that has a valid pointer if the object was still alive, or has a null stored pointer otherwise.
In practice, there's a much more common mistake that I've made - more than once, in fact.
If you declare your class like so (incorrectly!), then you might get a bad_weak_ptr
this when calling weak_from_this()
, among other weirdness with object lifetime.
class C : std::enable_shared_from_this<C> {
// things
};
The thing that's easy to forget is that the declaration needs to be public, so this should fix your problems.
class C : public std::enable_shared_from_this<C> {
// things
};
The root of the problem is that code within C
will see itself as inheriting from enabled_shared_from_this
, but external code won't, and so externally an external control block will be created to manage the object, instead of having it embedded (which is what C
code and subclasses will think is happening).
Happy sharing!