Form.Release + NIL

后端 未结 5 1289
无人及你
无人及你 2021-02-05 21:24

if Form.Release is called after using the form, it will free all related memory but not set the form variable to nil.

if not assigned (Form1) then
  begin
    Ap         


        
相关标签:
5条回答
  • 2021-02-05 21:33

    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.

    0 讨论(0)
  • 2021-02-05 21:36

    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.

    0 讨论(0)
  • 2021-02-05 21:46

    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.

    0 讨论(0)
  • 2021-02-05 21:50

    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?

    0 讨论(0)
  • 2021-02-05 21:52

    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.

    0 讨论(0)
提交回复
热议问题