`enable_shared_from_this`的作用是什么? [英] What is the usefulness of `enable_shared_from_this`?
问题描述
在阅读Boost.Asio示例时遇到了enable_shared_from_this
,在阅读了文档之后,我仍然迷失了如何正确使用它的方法.有人可以给我一个例子,解释使用此类的合理性.
I ran across enable_shared_from_this
while reading the Boost.Asio examples and after reading the documentation I am still lost for how this should correctly be used. Can someone please give me an example and explanation of when using this class makes sense.
推荐答案
当您拥有的全部是this
时,它使您可以将有效的shared_ptr
实例获取到this
.没有它,您将无法将shared_ptr
升级为this
,除非您已经有一个成员.来自关于enable_shared_from_this 的增强文档的示例:>
It enables you to get a valid shared_ptr
instance to this
, when all you have is this
. Without it, you would have no way of getting a shared_ptr
to this
, unless you already had one as a member. This example from the boost documentation for enable_shared_from_this:
class Y: public 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
}
方法f()
返回有效的shared_ptr
,即使它没有成员实例.请注意,您不能简单地这样做:
The method f()
returns a valid shared_ptr
, even though it had no member instance. Note that you cannot simply do this:
class Y: public enable_shared_from_this<Y>
{
public:
shared_ptr<Y> f()
{
return shared_ptr<Y>(this);
}
}
此共享指针返回的共享指针的引用计数与正确"的共享指针的引用计数不同,并且其中的一个指针最终将丢失并在删除对象时保持悬挂的引用.
The shared pointer that this returned will have a different reference count from the "proper" one, and one of them will end up losing and holding a dangling reference when the object is deleted.
enable_shared_from_this
已成为C ++ 11标准的一部分.您也可以从那里获得它,也可以从中获得它.
enable_shared_from_this
has become part of C++ 11 standard. You can also get it from there as well as from boost.
这篇关于`enable_shared_from_this`的作用是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!