gpt4 book ai didi

delphi - 如何正确使用ARC与接口(interface)?

转载 作者:行者123 更新时间:2023-12-03 15:54:38 26 4
gpt4 key购买 nike

我无法理解带有接口(interface)的 ARC 到底如何工作。在大多数教程中,我读到将接口(interface)设置为 nil 将调用 _Release,当 ARC 计数器达到零时,它将调用 Destroy。我读过一些教程,但我还不清楚。

type
IXXX = interface(IInterface)
end;

TXXX = class(TInterfacedPersistent, IXXX)
public
constructor Create;
destructor Destroy; override;
end;


procedure TForm1.Button4Click(Sender: TObject);
var
intf: IXXX;
begin
intf := TXXX.Create; // IntfCopy will be called. Message "create"
intf := nil; // IntfClear will be called. No message "destroy"
end;

{ TXXX }

constructor TXXX.Create;
begin
inherited;

showmessage('create');
end;

destructor TXXX.Destroy;
begin
showmessage('destroy');

inherited;
end;

当我运行这个程序时,我会收到一条消息“create”,但没有消息“destroy”。我查看了汇编代码,发现调用了 System._IntfCopySystem._IntfClear

查看 System._IntfClear 可以清楚地看出,当 Source 为 nil 时,不会调用 _Release,对于 intf 来说也是如此: =零。因此,难怪该对象永远不会被销毁。

那么如何正确使用ARC呢?

A blog建议不要接触接口(interface),而只使用非引用计数版本。我知道如何重写 _AddRef_Release 来绕过/禁用 ARC,但我想使用 ARC,除非有充分的理由不使用它。

(使用Delphi 6)

最佳答案

您派生的类,TInterfacedPersistent 在其 documentation 中有这样的说法。 :

TInterfacedPersistent, like all persistent objects, supports the ability to read and write its properties to and from a stream. In addition, it supplies a default implementation of the IInterface methods (_AddRef, _Release, and QueryInterface). This default implementation simply passes these calls on to the interface of the persistent object's Owner, if any.

当引用计数降至零时,当然会调用_Release。但随后什么也没有发生,因为你的对象没有所有者。

如果您希望使用引用计数来管理生命周期,那么您应该从 TInterfacedObject 派生。或者提供 _AddRef_Release 的实现,对引用进行计数并在引用计数降至零时销毁对象。使用TInterfacedObject 作为如何实现它的模板。

无论如何,您链接到的文章包含非常糟糕的建议。不要理会它。如果要使用接口(interface),请让引用计数管理生命周期,并仅通过接口(interface)引用对象。

关于delphi - 如何正确使用ARC与接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24234126/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com