gpt4 book ai didi

delphi - 如何释放 TInterfacedObject 中的 TObject 成员

转载 作者:行者123 更新时间:2023-12-03 18:07:29 25 4
gpt4 key购买 nike

我知道一个接口(interface)对象是引用计数的,所以不需要手动释放它。但是如果它有一个 TObject 继承的成员,我应该在析构函数中手动释放这个成员吗?

考虑以下代码:

program Project2;

{$APPTYPE CONSOLE}

{$R *.res}

uses
System.SysUtils,
System.Classes;

type
ITestInterface = interface(IInvokable)
['{A7BDD122-7DC6-4F23-93A2-B686571AB2C8}']
procedure TestMethod;
end;

TTestObj = class(TInterfacedObject, ITestInterface)
constructor Create;
destructor Destroy; override;
private
FData: TStrings;
public
procedure TestMethod;
end;

{ TTestObj }

constructor TTestObj.Create;
begin
FData := TStringList.Create;
end;

destructor TTestObj.Destroy;
begin
Writeln('Destroy'); // This line won't apear in the console ouput as the destructor won't be called.
FData.Free; // Who guarantees this member will be freed ?

inherited;
end;

procedure TTestObj.TestMethod;
begin
Writeln('TestMethod');
end;

{ Main }

procedure Main;
var
TestObj: TTestObj;
begin
TestObj := TTestObj.Create;
TestObj.TestMethod;
TestObj := nil; // TestObj should be freed at this moment ?
end;

begin
Writeln('Program start!');
Main;
Writeln('Program end.');
Readln;
end.

程序输出:
Program start!
TestMethod
Program end.

这意味着构造函数没有被调用,成员 FData没有被释放?

我该怎么办 ?提前致谢。

最佳答案

TTestObj中的代码很好。您必须实现一个销毁 FData 的析构函数。正如你所做的那样。

问题出在其他地方。接口(interface)对象没有被销毁,因为您永远不会触发任何引用计数。您需要通过接口(interface)变量引用接口(interface)对象。代替

TestObj: TTestObj


TestObj: ITestInterface

进行此更改后,接口(interface)引用代码将在您首次分配给 TestObj 时添加引用。多变的。

顺便说一句,你不需要这条线
TestObj := nil

TestObj变量超出范围,引用计数将降至零,实现对象将被销毁。

关于delphi - 如何释放 TInterfacedObject 中的 TObject 成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48983070/

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