I'm using boost's shared pointers, and enable_shared_from_this
to enable returning a shared pointer to this. Code looks like this:
class foo : public boost::enable_shared_from_this<foo>
{
boost::shared_ptr<foo> get()
{
return shared_from_this();
}
}
Why would shared_from_this throw a weak_ptr_cast exception?
If you declared foo on the stack, so that there are no other shared pointers to foo. For example:
void bar()
{
foo fooby;
fooby.get();
}
fooby.get() would throw the weak_ptr_cast
exception.
To get around this, declare fooby
on the heap:
void bar()
{
boost::shared_ptr<foo> pFooby = boost::shared_ptr<foo>(new foo());
pFooby->get();
}
Another possibility is that you're trying to use shared_from_this
before the constructor is done, which would again try to return a shared pointer that doesn't exist yet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With