Why are Delphi objects assigned even after calling .Free?

后端 未结 4 1134
遥遥无期
遥遥无期 2020-11-30 04:58

In Delphi, why does the Assigned() function still return True after I call the destructor?

The below example code will write \"sl is still assigned\" to the console.

4条回答
  •  误落风尘
    2020-11-30 05:19

    If you use sl.Free, the object is freed but the variable sl still points to the now invalid memory.

    Use FreeAndNil(sl) to both free the object and clear the pointer.

    By the way, if you do:

    var
      sl1, sl2: TStringList;
    begin
      sl1 := TStringList.Create;
      sl2 := sl1;
      FreeAndNil(sl1);
      // sl2 is still assigned and must be cleared separately (not with FreeAndNil because it points to the already freed object.)
    end;
    
    
    
    
    procedure TObject.Free;
    asm
        TEST    EAX,EAX
        JE      @@exit              // Jump to exit if pointer is nil.
        MOV     ECX,[EAX]           
        MOV     DL,1
        CALL    dword ptr [ECX].vmtDestroy  // Call cleanup code (and destructor).
    @@exit:
    end;
    

提交回复
热议问题