Accessing shared_ptr for this pointer

2019-09-18 06:09发布

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

1条回答
乱世女痞
2楼-- · 2019-09-18 06:36

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 of main and once when the last shared_ptr went away.

Perhaps you want:

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

Here, the instance is destroyed when its last shared_ptr goes away. That may occur at the end of main, but if foo squirrels away a copy of the shared_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.

查看更多
登录 后发表回答