简体   繁体   English

访问此指针的shared_ptr

[英]Accessing shared_ptr for this pointer

Is there a way to get access to the shared_ptr for this: 有没有办法为此访问shared_ptr:

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. 当我运行该程序时,执行bar后会出现一个segafult。 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. y的生存期由共享指针管理,或者当它创建于其上的堆栈帧终止时超出范围。 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. 如果此代码可以以某种方式起作用,它将破坏y两次,一次是在main末尾超出范围时,一次是在最后一次shared_ptr消失时。

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. 在这里,当实例的最后shared_ptr消失时,实例被销毁。 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. 这可能发生在main的末尾,但是如果foo松散了shared_ptr的副本,则它可以延长对象的生存期。 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. 如果无法动态管理对象的生存期,则此方法将无效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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