code_junkie

Why are Delphi objects assigned even after calling .Free?

Nov 11th, 2011
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.15 KB | None | 0 0
  1. program Project1;
  2. {$APPTYPE CONSOLE}
  3. uses SysUtils, Classes;
  4.  
  5. var
  6. sl : TStringList;
  7.  
  8. begin
  9. sl := TStringList.Create;
  10. sl.Free;
  11. if Assigned(sl) then
  12. WriteLn('sl is still assigned')
  13. else
  14. WriteLn('sl is not assigned');
  15. end.
  16.  
  17. procedure FreeAndNil(var Obj);
  18. var
  19. P: TObject;
  20. begin
  21. P := TObject(Obj);
  22. TObject(Obj) := nil; // clear the reference before destroying the object
  23. P.Free;
  24. end;
  25.  
  26. procedure TObject.Free;
  27. asm
  28. TEST EAX,EAX
  29. JE @@exit
  30. MOV ECX,[EAX]
  31. MOV DL,1
  32. CALL dword ptr [ECX].vmtDestroy
  33. @@exit:
  34. end;
  35.  
  36. var
  37. sl1, sl2: TStringList;
  38. begin
  39. sl1 := TStringList.Create;
  40. sl2 := sl1;
  41. FreeAndNil(sl1);
  42. // sl2 is still assigned and must be cleared separately (not with FreeAndNil because it points to the already freed object.)
  43. end;
  44.  
  45.  
  46.  
  47.  
  48. procedure TObject.Free;
  49. asm
  50. TEST EAX,EAX
  51. JE @@exit // Jump to exit if pointer is nil.
  52. MOV ECX,[EAX]
  53. MOV DL,1
  54. CALL dword ptr [ECX].vmtDestroy // Call cleanup code (and destructor).
  55. @@exit:
  56. end;
  57.  
  58. if Obj != NIL then
  59. vmtDestroy(obj); // which is basically the destructor/deallocator.
Add Comment
Please, Sign In to add comment