gpt4 book ai didi

delphi - 如何清除字符串列表中的指针?

转载 作者:行者123 更新时间:2023-12-02 17:09:36 25 4
gpt4 key购买 nike

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

例如:

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)。

提前谢谢

最佳答案

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

关于delphi - 如何清除字符串列表中的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15086408/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com