【发布时间】:2014-06-15 21:07:17
【问题描述】:
我无法理解带有接口的 ARC 究竟是如何工作的。在大多数教程中,我读过将接口设置为 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._IntfCopy 和System._IntfClear。
查看System._IntfClear 清楚地表明,当Source 为nil 时不会调用_Release,intf := nil 也是如此。所以难怪为什么对象永远不会被销毁。
那么如何正确使用ARC呢?
A blog 建议不要接触接口,而只使用非引用计数版本。我知道如何覆盖 _AddRef 和 _Release 以绕过/禁用 ARC,但我想使用 ARC,除非有充分的理由不使用它。
(使用 Delphi 6)
【问题讨论】:
-
您说使用 Delphi 6 -- 我假设您的意思是 Delphi XE6,因为 Delphi 6 不支持 ARC,仅支持接口引用计数。
-
我指的是 Delphi 6。对于“Interface ARC”,我指的是接口的 ARC。我知道普通对象在 Delphi 6 中没有 ARC/GC。
标签: delphi interface automatic-ref-counting