如何在Delphi中实现引用计数对象 [英] How to implement reference counted objects in Delphi

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

问题描述

我有一个像结构图。我不知道什么时候以传统的Delphi方式摧毁对象,而是要实现类似引用计数对象的东西。我知道我可以使用object.GetReference和object.Release而不是Free,并使用一个私有变量进行引用计数,但是有没有更好的方法?



谢谢

解决方案

如果您在确定正确的方法(位置,顺序等)破坏Delphi程序中的标准对象时遇到问题,那么使用引用计数的对象或接口就不会帮助你了。



我明白你希望图中的节点保持对对方的引用,没有对象的引用,应该被自动销毁。但是考虑两个节点每个都可以引用另一个节点的事实,并且引用计数将永远不会再次达到0,因此这些对象将永远不会被释放。您将需要手动中断至少一个引用/依赖关系。如果你还要这样做,那么你也可以跳过参考计数。有关更多信息,请参阅有关弱引用的维基百科文章。接口可以在Delphi中用于引用计数,但弱参考只能通过巧妙的类型转换来维护。有关示例,请参阅 this源代码及其注释



您可能想要探索的一个想法是保持对象的标准生命周期管理,并让图形对象保持跟踪依赖关系。



让每个图形对象都具有与其连接的其他对象的列表。现在,您可以简单地释放任何对象,列表的内务处理代码将删除对所有其他对象销毁的对象的所有引用。如果要修改图形,只需释放要删除的节点,并且依赖关系将被更新。如果要销毁整个图形,只需销毁所有节点。基本上,您有一个节点列表(所有权,生命周期管理)和用于描述图形的另一个数据结构。


I have a graph like structure. I don't know exactly when to destroy the objects in traditional Delphi manner, instead I would like to implement something like reference counted objects. I know that I can use something like object.GetReference and object.Release instead of Free, and use a private variable for reference counting, but is there any better way?

Thanks

解决方案

If you have problems determining the correct way (place, order and so on) of destroying standard objects in a Delphi program, then using reference counted objects or interfaces instead will not help you at all.

I understand that you want the nodes in a graph to keep references to each other, and when there are no references left to an object, it should be destroyed automatically. But consider the fact that two nodes can each have a reference to the other node, and the ref count will never reach 0 again, so that those objects will never be freed. You will need to break at least one of the references / dependencies manually. And if you have to do this anyway, then you can as well skip reference counting altogether. For some more information see the Wikipedia article about weak references. Interfaces can be used in Delphi for reference counting, but weak references can only be maintained with clever typecasting. For an example see this source code and its comments.

One idea that you might want to explore is to keep the standard lifetime management for your objects, and let the graph objects keep track of the dependencies instead.

Let each graph object have a list of other objects that it has connections with. Now you can simply free any of the objects, and the housekeeping code for the list will remove all references to the object being destroyed from all other objects. If you want to modify the graph you simply free the nodes that you want removed, and the dependencies will be updated. If you want to destroy the whole graph, just destroy all nodes. Basically you have a list of nodes (ownership, lifetime management) and another data structure for describing the graph.

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

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