获取一个boost :: shared_ptr的这个 [英] Getting a boost::shared_ptr for this
问题描述
我正在广泛使用升压的:在我的code的shared_ptr
。事实上,大多数在堆中分配的对象是由的shared_ptr
举行。不幸的是,这意味着我无法通过这个
成需要一个的shared_ptr
任何功能。考虑这个code:
I am making extensive use of boost:shared_ptr
in my code. In fact, most of the objects that are allocated on the heap are held by a shared_ptr
. Unfortunately this means that I can't pass this
into any function that takes a shared_ptr
. Consider this code:
void bar(boost::shared_ptr<Foo> pFoo)
{
...
}
void Foo::someFunction()
{
bar(this);
}
这里有两个问题。首先,这将不会编译,因为T *构造的shared_ptr
是明确的。其次,如果我强迫它来建立与巴(提高:: shared_ptr的&LT;富&GT;(本))
我将创建第二个共享指针,以我的对象,最终将导致以双删除。
There are two problems here. First, this won't compile because the T* constructor for shared_ptr
is explicit. Second, if I force it to build with bar(boost::shared_ptr<Foo>(this))
I will have created a second shared pointer to my object that will eventually lead to a double-delete.
这使我想到我的问题:有没有得到任何标准模式从这些对象的一个方法中存在,你知道现有的共享指针的副本?采用侵入式引用计数在这里我唯一的选择?
This brings me to my question: Is there any standard pattern for getting a copy of the existing shared pointer you know exists from inside a method on one of those objects? Is using intrusive reference counting my only option here?
推荐答案
您可以从<一个派生href=\"http://www.boost.org/doc/libs/1_36_0/libs/smart_ptr/enable_shared_from_this.html\">enable_shared_from_this然后你可以使用shared_from_this()而不是本,以一个共享指针产卵到你自己的对象。
You can derive from enable_shared_from_this and then you can use "shared_from_this()" instead of "this" to spawn a shared pointer to your own self object.
实例链接:
#include <boost/enable_shared_from_this.hpp>
class Y: public boost::enable_shared_from_this<Y>
{
public:
shared_ptr<Y> f()
{
return shared_from_this();
}
}
int main()
{
shared_ptr<Y> p(new Y);
shared_ptr<Y> q = p->f();
assert(p == q);
assert(!(p < q || q < p)); // p and q must share ownership
}
这是(),而这是一个好主意,当从一个成员函数产卵线程的boost ::绑定到shared_from_this。它将确保对象不会被释放。
It's a good idea when spawning threads from a member function to boost::bind to a shared_from_this() instead of this. It will ensure that the object is not released.
这篇关于获取一个boost :: shared_ptr的这个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!