Is there a way to get access to the shared_ptr for this:
e.g.
#include <boost/enable_shared_from_this.hpp>
#include <boost/shared_ptr.hpp>
#include <cassert>
class Y: public boost::enable_shared_from_this<Y>
{
public:
void foo();
void bar();
boost::shared_ptr<Y> f()
{
return shared_from_this();
}
};
void Y::foo()
{
boost::shared_ptr<Y> p(this);
boost::shared_ptr<Y> q = p->f();
q->bar();
p.reset();
q.reset();
}
void Y::bar()
{
std::cout << __func__ << std::endl;
}
int main()
{
Y y;
y.foo();
}
When I run the program I get a segafult after execution of bar. I do understand the reason for seg-fault.
My final goal is to have a weak pointer and then a call back.
Thanks
Either
y
's lifetime is managed by shared pointers or it goes out of scope when the stack frame it's created on terminates. Make up your mind and stick with it.If this code could work somehow, it would destroy
y
twice, once when it went out of scope at the end ofmain
and once when the lastshared_ptr
went away.Perhaps you want:
Here, the instance is destroyed when its last
shared_ptr
goes away. That may occur at the end ofmain
, but iffoo
squirrels away a copy of theshared_ptr
, it can extend the lifetime of the object. It can squirrel away a weak pointer, and perhaps tell in the destructor of the global object that the object is gone.The point of a weak pointer is to be able to promote it to a strong pointer which can extend the object's lifetime. This won't work if there's no way to dynamically manage the object's lifetime.