1

我不明白下面的物体在哪里以及如何清除它们?

例如:

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), pointer(i)) 中,我没有创建任何对象。有没有物体?如何清除 inttostr(i) 和 pointer(i)。

先感谢您

4

1 回答 1

6

不需要清除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行以创建内存泄漏,看看会发生什么。

于 2013-02-26T10:25:57.237 回答