引用计数智能指针的引用计数是如何工作的?

2023-09-26C/C++开发问题
8

本文介绍了引用计数智能指针的引用计数是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

换句话说,实现如何跟踪计数?

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:

  1. 智能指针分配一个小的内存块来包含参考计数器.每个副本智能指针然后接收一个指向实际对象的指针和一个指向引用计数的指针.
  2. 除了对象指针,每个智能指针包含一个上一个和下一个指针,从而形成一个双向链表指向特定的智能指针目的.引用计数是隐含在列表中.当一个聪明指针被复制,它将自身添加到列表.销毁时,每个智能指针从列表.如果是最后一个然后它释放的列表引用的对象也是如此.

如果你去这里并滚动到底部,有一个很好的更清楚地解释这些方法的图表.

If you go here and scroll to the bottom, there is an excellent diagram which explains these methods much more clearly.

这篇关于引用计数智能指针的引用计数是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6