Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost weak_ptr_cast in shared_from_this()

Tags:

c++

boost

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?

like image 591
stevex Avatar asked Jan 19 '09 22:01

stevex


1 Answers

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.

like image 144
stevex Avatar answered Sep 17 '22 21:09

stevex