How does a reference-counting smart pointer#39;s reference counting work?(引用计数智能指针的引用计数是如何工作的?)
问题描述
换句话说,实现如何跟踪计数?
In other words, how does the implementation keeps track of the count?
是否有一个类似地图的对象可以被所有 shared_ptr
实例访问,其键是指针的地址,值是引用的数量?如果我必须实现一个 shared_ptr
,这是我想到的第一个想法.
Is there a map-like object maintained which is accessible by all the shared_ptr
instances whose key is the pointer's address and value is the number of references? If I've to implement a shared_ptr
, this is the first idea that's coming to my mind.
在这些引用计数智能指针的情况下,是否有可能发生内存泄漏?如果是这样,我该如何避免它们?
Is there a possibility for a memory leak in case of these reference-counting smart pointers? If so, how can I avoid them?
推荐答案
我见过两种不同的非侵入式方法来解决这个问题:
I've seen two different non-intrusive approaches to this:
- 智能指针分配一个小的内存块来包含参考计数器.每个副本智能指针然后接收一个指向实际对象的指针和一个指向引用计数的指针.
- 除了对象指针,每个智能指针包含一个上一个和下一个指针,从而形成一个双向链表指向特定的智能指针目的.引用计数是隐含在列表中.当一个聪明指针被复制,它将自身添加到列表.销毁时,每个智能指针从列表.如果是最后一个然后它释放的列表引用的对象也是如此.
如果你去这里并滚动到底部,有一个很好的更清楚地解释这些方法的图表.
If you go here and scroll to the bottom, there is an excellent diagram which explains these methods much more clearly.
这篇关于引用计数智能指针的引用计数是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:引用计数智能指针的引用计数是如何工作的?
基础教程推荐
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 使用从字符串中提取的参数调用函数 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01