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

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

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.

相关文章