简体   繁体   中英

Accessing shared_ptr for this pointer

Is there a way to get access to the 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 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 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM