Accessing the shared_ptr for this pointer

Is there a way to access shared_ptr for this:

eg.

#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 segafult after bar execution. I understand the reason for the seg-fault.

My end goal is to have a weak pointer and then a callback.

thank

0


source to share


1 answer


Either the lifetime is y

driven by shared pointers, or is out of scope when the stack frame created at its completion. Decide and stick to it.

If this code could work somehow, it would kill y

twice, once when it went out of scope at the end main

and once when the last one shared_ptr

left.

Maybe you want:



int main()
{
   std::shared_ptr<Y> y = std::make_shared<Y>();
   y->foo();
}

      

Here, the instance is destroyed when its last one shared_ptr

disappears. It can happen at the end main

, but if it foo

pops a copy shared_ptr

, it can extend the lifetime of the object. It can throw out a weak pointer and possibly tell the destructor of the global object that the object is gone.

The point of a weak pointer must be able to advance it to a strong pointer, which can extend the lifetime of an object. This will not work if there is no way to dynamically manage the object's lifetime.

0


source







All Articles