访问此指针的shared_ptr [英] Accessing shared_ptr for this pointer
问题描述
有一种方法可以访问shared_ptr:
Is there a way to get access to the shared_ptr for this:
例如。
#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();
}
当我运行程序时,我在执行bar后得到一个segafult。
我明白了seg-fault的原因。
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.
感谢
推荐答案
y
的生命周期由共享指针管理,或者当它创建的堆栈帧终止时超出范围。
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.
如果这段代码能以某种方式工作,它会破坏 y
两次,一次当 main
结束时超出范围,并且一旦最后一个 shared_ptr
消失了。
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.
也许你想要:
int main()
{
std::shared_ptr<Y> y = std::make_shared<Y>();
y->foo();
}
这里,实例被销毁时,其最后 shared_ptr
消失。这可能发生在 main
的结尾,但如果 foo
squirrels一份 shared_ptr
,它可以延长对象的生命周期。它可以松开一个弱指针,也许在全局对象的析构函数中告诉对象已经走了。
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.
这篇关于访问此指针的shared_ptr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!