且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-10-18 23:01:55

我看到两种不同的非侵入性方法:


  1. 智能指针分配一个小的
    内存块以包含
    引用计数器。
    智能指针的每个副本然后接收指向实际对象的
    指针和指向引用计数的
    指针。

  2. 除了对象指针,
    每个智能指针包含一个
    上一个和下一个指针,从而
    形成一个双向链接的
    的列表指向一个特定的
    对象的智能指针。引用计数是
    隐含在列表中。当智能
    指针被复制时,它将自己添加到
    列表中。在销毁时,每个
    智能指针将自己从
    列表中删除。如果它是
    列表中的最后一个,那么它也会释放
    引用的对象。

请访问此处并滚动到底部,有一个很好的图表,可以更清楚地解释这些方法。 / p>

In other words, how does the implementation keeps track of the count?

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. The smart pointer allocates a small block of memory to contain the reference counter. Each copy of the smart pointer then receives a pointer to the actual object and a pointer to the reference count.
  2. In addition to an object pointer, each smart pointer contains a previous and next pointer, thereby forming a doubly-linked list of smart pointers to a particular object. The reference count is implicit in the list. When a smart pointer is copied, it adds itself to the list. Upon destruction, each smart pointer removes itself from the list. If it's the last one in the list it then frees the referenced object as well.

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