我在这个代码里面要不要 Free?(100分)

  • 主题发起人 let_it_be
  • 开始时间
凡是您自己Create的东西,最好都自己Free
 
调用完之后一定要释放。

function TDataSet.GetBookmark: TBookmark;
begin
if BookmarkAvailable then
begin
GetMem(Result, FBookmarkSize);
GetBookmarkData(ActiveBuffer, Result);
end else
Result := nil;
end;

procedure TDataSet.FreeBookmark(Bookmark: TBookmark);
begin
FreeMem(Bookmark);
end;
 
aerobull的回答是比较好的代码风格,创建和释放在同一个方法内,清晰明了
 
另一个
class function TfmSendto.SendOut: boolean;
begin
with Create(Owner) do //Owner可以为Application或者其他Form,这样在Owner释放的时候会负责这个窗体的释放
try
ShowModal;
Result:=ModalResult=mrOk;
finally
Free
//这里最好加上,资源用完就释放是好的习惯
end;
end;
 

因为前面有Create 应该 free.
 
function TFrSlUser.getSelectUsers: TStringList;
begin
Result:=TStringList.Create;
result.add('aaaaa')
end;
.......
var
TempList: TStringList;
begin
TempList := getSelectUsers;
try
//执行语句
finally
TempList.Free;
end;
end;
//一定要用保护释放

我还是喜欢这样更好一点。
 
华旗的产品-爱国者MP3很烂,才用20天,耳机就脱胶,还说是外伤,不给任何维修等,哪个龟儿子再买爱国者MP3,甚至华旗的东西

如果不属实,天洙地灭
 
哦,回答的人还不少,现在我总算明白了一点,
函数内的 Result 的不应该在函数内 Free ,对不对?
----
另外的一个 Release 或者 Free 是可以不要的,
因为我 在OnClose 中将Action:=caFree,对不对?
 
真诚听课!感谢各位大富翁!
 
:let_it_be,
//函数内的 Result 的不应该在函数内 Free ,对不对?
是的噢.

//另外的一个 Release 或者 Free 是可以不要的,
//因为我 在OnClose 中将Action:=caFree,对不对?
当然不对啊.
action:=cafree是在form关闭时的,你如果在form 关闭前就create了N次.而没有free.
程序占用的资源会越来越大的啊.况且好的习惯就是create之后就用
try....finally的方式释放啊.




 
接受答案
 
aerobull:
我试过,好像是你说的不对,
要Free出错 AV, 不要不错。
Delphi的帮助都是这样说的。

Value Meaning

caNone The form is not allowed to close, so nothing happens.
caHide The form is not closed, but just hidden. Your application can still access a hidden form.
caFree The form is closed and all allocated memory for the form is freed.
caMinimize The form is minimized, rather than closed. This is the default action for MDI child forms.

If a form is an MDI child form, and its BorderIcons property is biMinimize, then the default Action is caMinimize. If a MDI child form does not have these settings, the default Action is caNone, meaning that nothing happens when the user attempts to close the form.

If a form is an SDI child form, Action defaults to caHide.

To close the form and free it in an OnClose event, set Action to caFree.

Note: When the application shuts down, the main form receives an OnClose event, but any child forms do not receive the OnClose event.
 
好像已经发过一次分的
 

Similar threads

S
回复
0
查看
3K
SUNSTONE的Delphi笔记
S
S
回复
0
查看
2K
SUNSTONE的Delphi笔记
S
I
回复
0
查看
396
import
I
I
回复
0
查看
686
import
I
顶部 底部