Why are Delphi objects assigned even after calling .Free?

后端 未结 4 1136
遥遥无期
遥遥无期 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条回答
  •  旧时难觅i
    2020-11-30 05:39

    Delphi VCL 'objects' are actually always pointers to objects, but this aspect is typically hidden from you. Just freeing the object leaves the pointer dangling around, so you should use FreeAndNil instead.

    The "Mysterious Assembler" translates roughly to:

    if Obj != NIL then
      vmtDestroy(obj);  // which is basically the destructor/deallocator.
    

    Because Free checks for NIL first, it's safe to call FreeAndNil multiple times...

提交回复
热议问题