我知道接口对象是引用计数的,因此不需要手动释放它。但如果它有一个 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
就像你所做的那样。
问题出在别处。接口对象不会被销毁,因为您永远不会触发任何引用计数。您需要通过接口变量引用接口对象。代替
TestObj: TTestObj
with
TestObj: ITestInterface
进行此更改后,接口引用代码将在您首次分配给TestObj
多变的。
顺便说一句,你不需要这条线
TestObj := nil
当。。。的时候TestObj
变量超出范围,引用计数将降至零,并且实现对象将被销毁。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)