关于对象释放问题,请帮忙看看

westuser 2011-09-08 06:13:25

procedure TForm1.Button1Click(Sender: TObject);
var
s:TStrings;
test:TTest;
begin
//test add object
s:=TStringList.Create;
test:=TTest.Create;
test.str:='test1';
test.id:=1;
s.AddObject(test.str,test);
test.Free;
test:=TTest.Create;
test.str:='test2';
test.id:=2;
s.AddObject(test.str,test);
test.Free;
CheckListBox1.Items:=s;
s.Free;
end;

该代码运行似乎没问题,可是我有一点疑问,s赋值给items后还需要手工释放吗?delphi组件不是会自动释放吗?还有最后那句s.free,我以为执行完这句对象被释放,应该什么都不显示,可是事实上显示正常。
...全文
108 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
hhkun0120 2011-09-09
  • 打赏
  • 举报
回复
首先,楼主,你的代码书写很有问题,同一个变量名两次创建并释放,代码可读性差;
其次,就如同
  s:=TStringList.Create;
test:=TTest.Create;
test.str:='test1';
test.id:=1;
s.AddObject(test.str,test);
test.Free;

这里一样,test对象free之后,s中依然加入了字符串‘test1’和整型‘1’,test对象被free不影响s。
同样道理,当你将s的内容添加到CheckListBox中时,free s 也不影响ListBox
火龙岛主 2011-09-09
  • 打赏
  • 举报
回复
这段代码有问题,会导致内存泄露。

unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Buttons, StdCtrls, CheckLst;

type
TTest = class
str: string;
id: integer;
end;

TForm1 = class(TForm)
btn1: TButton;
CheckListBox1: TCheckListBox;
BitBtn1: TBitBtn;
procedure btn1Click(Sender: TObject);
procedure BitBtn1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.btn1Click(Sender: TObject);
var
s:TStrings;
test:TTest;
begin
//test add object
s:=TStringList.Create;
test:=TTest.Create;
test.str:='test1';
test.id:=1;
s.AddObject(test.str,test);
test.Free;
test:=TTest.Create;
test.str:='test2';
test.id:=2;
s.AddObject(test.str,test);
test.Free;
CheckListBox1.Items:=s;
s.Free;
end;


procedure TForm1.BitBtn1Click(Sender: TObject);
var
vTest: TTest;
begin
vTest := TTest(CheckListBox1.Items.Objects[0]);
ShowMessage(vTest.str); //不能得到正确结果
end;

end.
rainychan2009 2011-09-08
  • 打赏
  • 举报
回复
指针、地址、内存
指针P存放的只是一段内存的地址
P.FREE
是释放P中存放地址指向的内存,P中还是有存放地址的,不过该地址指向的内存空间已经释放。
ZuoBaoquan 2011-09-08
  • 打赏
  • 举报
回复
为了开发者方便,Vcl里面有些属性使用起来是有歧义的,比如你写的
CheckListBox1.Items:=s;
咋看起来还以为是赋值一个引用,实际上调用的是Items属性的setter,里面类似于:
procedure TXXX.SetItems(value: TStrings);
begin
fItems.Assign(value);
end;
这个可以理解为字符串列表的Clone。建议你好好看看里面的代码,把思路整理整理:)
xinghun61 2011-09-08
  • 打赏
  • 举报
回复
CheckListBox1.Items:=s;是将s中的内容拷贝到CheckListBox1.Items中,它们是2个不同的对象,因此,对s的操作不会影响到CheckListBox1.Items,反之道理一样。

5,388

社区成员

发帖
与我相关
我的任务
社区描述
Delphi 开发及应用
社区管理员
  • VCL组件开发及应用社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧