给出下面的Delphi代码,在Foo
上将Free
替换为FormClose
,但是没有调用TFoo.Destroy
-因此,Bar
却没有被调用,从而导致内存泄漏?
我是否在这里错过了某些东西,或者不应该Foo。免费拨打Foo。在某个时候销毁?
Free
您必须使用重写标记析构函数的签名。
type
TBar = class
SomeInteger : integer;
end;
TFoo = class
Bar : TBar;
constructor Create();
destructor Destroy();
end;
var
Foo : TFoo;
implementation
constructor TFoo.Create;
begin
Bar := TBar.Create;
Bar.SomeInteger := 2;
end;
destructor TFoo.Destroy;
begin
Bar.Free;
Bar := nil;
showmessage('Destroyed!');
end;
procedure TForm10.FormCreate(Sender: TObject);
begin
Foo := TFoo.Create;
showmessage('Foo created');
end;
procedure TForm10.FormDestroy(Sender: TObject);
begin
Foo.Free;
Foo := nil;
end;
并且您应该在析构函数的末尾带有destructor Destroy(); override;
。但是由于您的类不是从TObject派生而来,所以我认为这没有关系。
销毁是虚拟的,因此您必须在子孙类中覆盖它。
inherited
没有覆盖,就不会调用您的析构函数,而将调用基类。
迟到总比想不到好。
我在这里遇到了相同的问题,但是在Delphi 10.3上使用myClass = class(TInterfacedObject)
TFoo = class
Bar : TBar;
constructor Create();
destructor Destroy(); override; // must add override here
end;
将完成它的工作-我希望-但是Destroy()永远不会执行,即使使用覆盖或虚拟命令也不会执行。
或;是否应该将Destroy方法留在接口类中,因为编译器会解决这个问题? myClassRef := Nil;
现在,这为什么呢?预先谢谢你。