【发布时间】:2016-03-13 14:14:15
【问题描述】:
我有以下两个类:
type
TItemProp = class
private
FItemPropName: string;
FItemPropValue: string;
public
constructor Create(AItemPropName, AItemPropValue: string);
class function GetItemProp(AHTMLElement: OleVariant; AProp: string): TItemProp;
property ItemPropName: string read FItemPropName;
property ItemPropValue: string read FItemPropValue;
end;
TTest = class
private
FName: string;
FProps: TList<TItemProp>;
FTest: TList<TTest>;
public
constructor Create(AName: string);
destructor Destoroy();
property Name: string read FName;
property ItemProps: TList<TItemProp> read FProps write FProps;
property Test: TList<TTest> read FTest write FTest;
end;
这里是TTest类的构造函数和析构函数的代码:
constructor TTest.Create(AName: string);
begin
Self.FName := AName;
Self.FProps := TList<TItemProp>.Create();
Self.FTest := TList<TTest>.Create();
end;
destructor TTest.Destoroy();
var
I: Integer;
begin
for I := 0 to Self.FTest.Count - 1 do
begin
Self.FTest[I].Free;
Self.FTest[I] := nil;
end;
Self.FProps.Free;
Self.FTest.TrimExcess;
Self.FTest.Free;
inherited;
end;
问题是这段代码正在泄漏内存。我应该如何重写析构函数以修复内存泄漏?
【问题讨论】:
-
这个类是否拥有包含在
FProps中的TItemProps?如果是,我看不到您释放这些对象。考虑改用TObjectList<TItemProp>和TObjectList<TTest>- 默认情况下这些是用[doOwnsValues]创建的,列表本身将管理从中删除的释放对象。 -
我恢复了您的编辑,它提出了一个新问题。请不要那样做。
标签: delphi memory-leaks destructor