引用计数智能指针的引用计数如何工作? [英] How does a reference-counting smart pointer's reference counting work?

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

问题描述

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



是否有一个地图类对象维护,可以通过 shared_ptr 实例的键是指针的地址,值是引用的数量?如果我要实现 shared_ptr ,这是我的想法的第一个想法。



在这些引用计数智能指针的情况下的内存泄漏的可能性?

解决方案

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


  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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆