谢谢
解决方案如果您在确定正确的方法(位置,顺序等)破坏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中实现引用计数对象
发布评论