如何跟踪对对象的引用? [英] How to keep track of the references to an object?

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

问题描述

在仍然需要手动分配内存和指针的世界中(Borland Delphi),我需要一个普遍的解决方案来解决我认为的普遍问题:

In a world where manual memory allocation and pointers still rule (Borland Delphi) I need a general solution for what I think is a general problem:

在给定的时刻,可以从多个位置(列表,其他对象等)引用一个对象.有没有一种很好的方法来跟踪所有这些引用,以便在对象被销毁时可以对其进行更新?

At a given moment an object can be referenced from multiple places (lists, other objects, ...). Is there a good way to keep track of all these references so that I can update them when the object is destroyed? ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­

推荐答案

如果您想将更改通知他人,则应实施观察者模式" . Delphi已经为TComponent后代为您完成了此任务.您可以调用TComponent.FreeNotification方法,并在其他组件被销毁时通知您的对象.它通过调用Notification方法来做到这一点.您可以通过调用TComponent.RemoveFreeNotification从通知列表中删除自己.另请参见此页面.

If you want to notify others of changes you should implement the "Observer Pattern". Delphi has already done that for you for TComponent descendants. You can call the TComponent.FreeNotification method and have your object be notified when the other component gets destroyed. It does that by calling the Notification method. You can remove yourself from the notification list by calling TComponent.RemoveFreeNotification. Also see this page.

大多数垃圾收集器不允许您获取参考列表,因此在这种情况下它们将无济于事.如果您要使用接口,Delphi可以进行引用计数,但是再次需要您自己跟踪引用.

Most Garbage Collectors do not let you get a list of references, so they won't help in this case. Delphi can do reference counting if you would use interfaces, but then again you need to keep track of the references yourself.

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

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