Form.Release + NIL

瘦欲@ 提交于 2019-12-03 02:39:27

Put the line

  Form1 := nil;  

just after the call to Release.

Release is just posting a CM_RELEASE message to the Form which allows the Form to finish what's in its queue (event handlers) before handling the CM_RELEASE message which means normally just calling Free.
So, after calling Release, you should not assume that the Form variable still points to a valid Form, thus putting nil into the variable.

François

Release is just a (potentially) deferred Free. The 1st thing you should do after calling Release is nilling the variable.
Then, you'll be safe even if some code tries to reference Form1 before it is actually destroyed. In a case like in your code, it would just safely recreate another Form1 for the new usage without bothering the one being destroyed.

Of you could just always call this:

procedure FreeOrReleaseAndNil(var Obj);
var
  Temp: TObject;
begin
  Temp := TObject(Obj);
  Pointer(Obj) := nil;
  if Temp is TCustomForm then
    TCustomForm(Temp).Release
  else
    Temp.Free;
end;

Be sure to check the type after casting to a TObject as you can't test the type of Obj. This should be safe since like Free, Release is non-virtual.

As is mentioned Release is only a deferred Free for a form to use if it wants to Close/Free itself. Other then being deferred it does nothing different from Release. So there is no use in calling Release in that example. Calling Free seems to be more logical. And you can set it to nil after calling Free or use FreeAndNil.

If you still want to use Release that is fine. Just setting the variable value to nil works. Doing that does not make the forum behave differently. But remember that in this case it is more efficient and more deterministic to call Free instead of Release. My preference is to only use Release where is really needed.

In Delphi Win32, the appropriate way to free objects is to call

FreeAndNil(Form1)

This does both jobs in a single call.

However, I have a sneaking feeling there's more to your question than meets the eye. Are you using Delphi for .NET - and if so, which version?

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!