是否有像 TInterfacedObject 这样的非引用计数基类?
我需要一个类似 TInterfacedObject
的基类,但没有引用计数(因此是一种 TNonRefCountedInterfacedObject
)。
这实际上是我第n次需要这样的课程,不知怎的,我总是一次又一次地编写(阅读:复制和粘贴)我自己的课程。我不敢相信没有我可以使用的“官方”基类。
RTL 中是否有一个实现 IInterface
的基类,但没有引用计数,我可以从中派生我的类?
I need a base class like TInterfacedObject
but without reference counting (so a kind of TNonRefCountedInterfacedObject
).
This actually is the nth time I need such a class and somehow I always end up writing (read: copy and pasting) my own again and again. I cannot believe that there is no "official" base class I can use.
Is there a base class somewhere in the RTL implementing IInterface
but without reference counting which I can derive my classes from?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
在 Generics.Defaults 单元中定义了一个 TSingletonImplementation 类。适用于 Delphi 2009 及更高版本。
In the unit Generics.Defaults there is a class TSingletonImplementation defined. Available in Delphi 2009 and above.
您可以考虑TInterfacedPercient。如果您不重写 GetOwner,它不会进行引用计数。
You might consider TInterfacedPersistent. If you don't override GetOwner it does no ref-counting.
我这样做了。它可以用来代替 TInterfacedObject,带或不带引用计数。它还有一个 name 属性 - 在调试时非常有用。
I did this. It can be used in place of TInterfacedObject with or without reference counting. It also has a name property - very useful when debugging.
从 Delphi 11 Embarcadero 开始,将 TNoRefCountObject 添加到系统单元。以下是发行说明中的注释:
As of Delphi 11 Embarcadero added TNoRefCountObject to the System unit. Here's the note from the release notes:
我不知道任何开箱即用的基类,所以我编写了自己的基类(像你一样)。只需将其放入通用实用程序单元中即可完成。
I don't know of any out-of-the-box base class, so I wrote my own (like you). Just put it in a common utils unit and you are done.
没有这样的类,但是您可以轻松编写自己的类,正如其他人所展示的那样。然而,我确实想知道为什么你需要它。根据我的经验,即使您想混合对象和接口引用,也很少真正需要这样的类。
另请注意,当您使用此类时,您仍然需要在此类对象离开作用域之前以及释放对象之前将此类对象的任何接口引用设置为 nil。否则,您可能会遇到运行时尝试在已释放对象上调用 _Release 的情况,这往往会导致无效指针异常。
IOW,我建议反对使用这样的类。
There is no such class, but you can easily write your own, as others have shown. I do, however, wonder why you would need it. In my experience, there is seldom a real need for such a class, even if you want to mix object and interface references.
Also note that when you use such a class, you'll still have to take care of setting any interface references you have to such an object to nil before they leave scope and before you free the object. Otherwise you might get the situation the runtime tries to call _Release on a freed object, and that tends to cause an invalid pointer exception.
IOW, I would advise against using such a class at all.