Why are Delphi objects assigned even after calling .Free?

后端 未结 4 1138
遥遥无期
遥遥无期 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:16

    We have simple rules:

    1. If you want to use Assigned() to check if an object Obj is already created or not, then make sure you use FreeAndNil(Obj) to free it.

    2. Assigned() only says if an address is assigned or not.

    3. The local object reference is always assigned a garbage address (some random address), so it is good to set it to nil before using it.

    Example: (This is not the full code)

    {Opened a new VCL application, placed a Button1, Memo1 on the form
    Next added a public reference GlobalButton of type TButton
    Next in OnClick handler of Button1 added a variable LocalButton 
    Next in body, check if GlobalButton and LocalButton are assigned}
    
      TForm2 = class(TForm)
        Button1: TButton;
        Memo1: TMemo;
        procedure Button1Click(Sender: TObject);
      private
        { Private declarations }
      public
        { Public declarations }
        GlobalButton: TButton;
      end;
    
    procedure TForm2.Button1Click(Sender: TObject);
    var
      LocalButton: TButton;
    begin
      if Assigned(GlobalButton) then  
        Memo1.Lines.Add('GlobalButton assigned');
      if Assigned(LocalButton) then  
        Memo1.Lines.Add('LocalButton assigned');
    end;
    

提交回复
热议问题