我不明白下面的对象在哪里以及如何清除它们?
例如:
public
Alist: TStringlist;
..
procedure TForm1.FormCreate(Sender: TObject);
begin
Alist:=Tstringlist.Create;
end;
procedure TForm1. addinstringlist;
var
i: integer;
begin
for i:=0 to 100000 do
begin
Alist.add(inttostr(i), pointer(i));
end;
end;
procedure TForm1.clearlist;
begin
Alist.clear;
// inttostr(i) are cleared, right?
// Where are pointer(i)? Are they also cleared ?
// if they are not cleared, how to clear ?
end;
procedure TForm1. repeat; //newly added
var
i: integer;
begin
For i:=0 to 10000 do
begin
addinstringlist;
clearlist;
end;
end; // No problem?
我使用Delphi 7.在delphi 7.0帮助文件中,它说:
AddObject method (TStringList)
Description
Call AddObject to add a string and its associated object to the list.
AddObject returns the index of the new string and object.
Note:
The TStringList object does not own the objects you add this way.
Objects added to the TStringList object still exist
even if the TStringList instance is destroyed.
They must be explicitly destroyed by the application.
在我的程序Alist.add(inttostr(i),指针(i))中,我没有创建任何对象。是否有物体? 如何清除inttostr(i)和指针(i)。
提前谢谢
答案 0 :(得分:5)
无需清除Pointer(I)
,因为指针不引用任何对象。它是一个存储为指针的整数。
建议:如果您不确定您的代码是否泄漏或者没有编写简单的测试并使用
ReportMemoryLeaksOnShutDown:= True;
如果您的代码泄露,您将收到有关关闭测试应用程序的报告。
您添加的代码不会泄漏。如果您想检查它,请写下这样的测试:
program Project2;
{$APPTYPE CONSOLE}
uses
SysUtils, Classes;
var
List: TStringlist;
procedure addinstringlist;
var
i: integer;
begin
for i:=0 to 100 do
begin
List.addObject(inttostr(i), pointer(i));
end;
end;
procedure clearlist;
begin
List.clear;
end;
procedure repeatlist;
var
i: integer;
begin
For i:=0 to 100 do
begin
addinstringlist;
clearlist;
end;
end;
begin
ReportMemoryLeaksOnShutDown:= True;
try
List:=TStringList.Create;
repeatlist;
List.Free;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.
尝试评论List.Free
行以创建内存泄漏,看看会发生什么。