请参阅下面的代码.为了简单起见,我删除了很多代码,但剩下的代码仍然很长,对不起:(
IObserver = interface
['{1DD212F8-BD5E-47BF-9A3B-39EF7B9D99B5}']
procedure Update(Observable: IObservable);
end;
TObserver = class abstract (TSingletonImplementation, IObserver)
strict protected
//...
public
constructor Create;
destructor Destroy; virtual;
//IObserver
procedure Update(Observable: IObservable); virtual; abstract;
//...
end;
TShapeModification = class abstract (TObserver)
strict protected
//...
public
//Doesn't have a constructor
end;
TRangePointModification = class(TShapeModification)
strict private
//...
public
constructor Create(...);
//...
end;
constructor TRangePointModification.Create(...);
begin
inherited Create;
//...
end;
Run Code Online (Sandbox Code Playgroud)
然后在某个时候:
TClientClass = class
strict private
fList: TObjectList<TShapeModification>;
public
constructor Create();
destructor Destroy(); override;
procedure Add(ShapeModification: TShapeModification);
end;
constructor TClientClass.Create;
begin
Self.fList:=TObjectList<TShapeModification>.Create(true);
end;
destructor TClientClass.Destroy;
begin
Self.fList.Clear;
FreeAndNil(Self.fList);
end;
Run Code Online (Sandbox Code Playgroud)
最后,在某些时候:
var
MyClient: TClientClass;
begin
MyClient:=TClientClass.Create();
MyClient.Add(TRangePointModification.Create());
MyClient.Free;
end;
Run Code Online (Sandbox Code Playgroud)
当MyClient
释放时,TClientClass
析构函数被调用,然后内部fList
应该被清除但是TRangePointModification
(from TObserver
)的析构函数不被调用.为什么不?
(我使用的是Delphi 10.2 Tokyo)
Ste*_*nke 14
查看警告 - 编译器会告诉您错误:
W1010 Method 'Destroy' hides virtual method of base type ...
Run Code Online (Sandbox Code Playgroud)
总是穿上override
你的析构函数(不是虚拟的!) - 否则调用Free
将不会执行你输入的代码.
所以作为基本建议:
总是编写产生零警告或提示的代码 - 它们很可能指向您迟早会遇到的缺陷
在您怀疑有缺陷的代码中加入一个断点 - 即使忽略了编译器警告,您也会看到调用Clear
始终没有