What is the usefulness of `enable_shared_from_this`?(`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.
推荐答案
当你只有 这个代码>.没有它,您将无法获得 shared_ptr 到 this,除非您已经拥有一个成员.此示例来自 enable_shared_from_this 的 boost 文档:>
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 标准的一部分.您也可以从那里和 boost 获取它.
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` 有什么用处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:`enable_shared_from_this` 有什么用处?
基础教程推荐
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- c++ STL设置差异 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
