2013-02-26 57 views
1

我不明白下面的對象在哪裏以及如何清除它們?如何清除stringlist中的指針?

例如:

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)指針(我)),我沒有創建任何對象。那裏有沒有對象? 如何清除inttostr(i)和指針(i)。

預先感謝您

回答

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行創建一個內存泄漏,並看看會發生什麼。

+0

非常感謝。我添加了重複過程。請參見。沒問題?我應該如何測試ReportMemoryLeaksOnShutDown:= True;? – Warren 2013-02-26 10:51:12

+0

@Serg謝謝大家 – Warren 2013-02-26 11:24:04