对象的引用计数 [英] Reference-counting for objects

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

问题描述

在我的代码中,我使用一个小数据存储类,它在不同的地方创建。为了避免内存泄漏和简化的事情,我想使用引用计数,所以我做了

In my code I use a small data-storing class, which is created in different places. To avoid memory leaks and simplify things, I want to use reference counting, so I did

type TFileInfo = class (TInterfacedObject, IInterface)

并删除我所有的手动调用TFileInfo.Free。不幸的是,Delphi报告了很多内存泄漏。搜索SO我发现以下问题解释为什么这不工作:

and removed all my manual calls to TFileInfo.Free. Unfortunately Delphi reported a lot of memory leaks. Searching on SO I found the following question explaining why this doesn't work:

为什么收集TInterfacedObject垃圾的后代?

这里有一个解决方法,但是需要我(至少如果我正确的话)写一个自定义界面IFileInfo并提供了很多getter和setter,我想避免。

There is a workaround presented there but it requires me (at least if i get it right) to write a custom interface IFileInfo and provide it with a lot of getters and setters, which I want to avoid.

编辑我应该补充说,我将​​创建FileInfo对象插入两种不同类型的哈希表:一个从TBucketList下降,另一个是从Codegear论坛的哈希映射实现。在内部他们都是用户指针,所以情况就像在另一个问题。

EDIT I should add that I insert the create FileInfo objects into two different kinds of hash tables: one descending from TBucketList and another one is a hash map implementation from the Codegear forum. Internally they both user pointers, so the situation is just like in the other question.

有没有其他的可能性,使Delphi中的对象使用引用计数?

Is there any other possibility to make objects in Delphi use reference-counting?

推荐答案

不幸的是,只有当您使用接口(在您的情况下是自定义界面IFileInfo)时,Delphi编译器才会生成必要的代码以使其仅限于引用计数。此外,如果将接口转换为指针(或TObject对象),则再次无法引用计数。例如,假设全局变量列表:TList:

Unfortunately, the Delphi compiler generates the necessary code to inc/dec reference count only when you use interfaces (in your case custom interface IFileInfo). Moreover, if interfaces are cast to pointer (or TObject for that matter), again no reference counting is possible. For example, assumming global variable list : TList:

var ifi : IFileInfo;
begin
  ifi := TFileInfo.Create;
  list.Add(TFileInfo(ifi));
end;

方法返回列表[list.Count - 1]将包含悬挂指针。

after the method returns list[list.Count - 1] will contain dangling pointer.

因此,接口不能用于将它们转换为指针的hashmap,所以hashmap实现必须将它们保持为IInterface。

So interfaces cannot be used in a hashmap that casts them to pointers, the hashmap implementation must keep them as IInterface.

这篇关于对象的引用计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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