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:
fooby.get() would throw the
weak_ptr_castexception.To get around this, declare
foobyon the heap:Another possibility is that you’re trying to use
shared_from_thisbefore the constructor is done, which would again try to return a shared pointer that doesn’t exist yet.