tags:

views:

993

answers:

1

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?

+5  A: 

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.

stevex