调用TObjectList.Clear时,不会释放TObjectList中的对象

Del*_*lmo 5 delphi

请参阅下面的代码.为了简单起见,我删除了很多代码,但剩下的代码仍然很长,对不起:(

  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将不会执行你输入的代码.

所以作为基本建议:

  1. 总是编写产生零警告或提示的代码 - 它们很可能指向您迟早会遇到的缺陷

  2. 在您怀疑有缺陷的代码中加入一个断点 - 即使忽略了编译器警告,您也会看到调用Clear始终没有