我在我的代码中广泛使用了 boost:shared_ptr
.事实上,在堆上分配的大多数对象都由一个shared_ptr
持有.不幸的是,这意味着我无法将 this
传递给任何采用 shared_ptr
的函数.考虑这个代码:
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);
}
这里有两个问题.首先,这不会编译,因为 shared_ptr
的 T* 构造函数是显式的.其次,如果我强制它使用 bar(boost::shared_ptr<Foo>(this))
构建,我将创建第二个指向我的对象的共享指针,最终将导致双重删除.
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?
您可以从 enable_shared_from_this 然后您可以使用shared_from_this()"而不是this"来生成指向您自己的 self 对象的共享指针.
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::bind 到 shared_from_this() 而不是 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!