Destructor class in TObject and NIL Delphi

2020-05-05 17:10发布

I am wondering why after I invoke Free method the object is not nil.
What I mean for example next class:

type Ta = class(TObject)
public
  i: integer;
  destructor Destroy; override;
end;

destructor Ta.Destroy;
begin
  inherited;
end;

procedure Form1.Button1;
var a: Ta;
begin
  a := Ta.Create;       
  a.Free;

  if a = nil then
    button1.Caption := 'is assigned' 
  else 
    button1.caption := 'is not assigned';
end;

My question is why after freeing the object is not nil and how will I make a to be nil after destructor without using a := nil?

2条回答
叼着烟拽天下
2楼-- · 2020-05-05 17:36

Explanation:

The variable a will only become nil when it is assigned nil. That means there needs to be a := nil in code, which is now missing.

Free is just a method, working on an instance of the Ta class. Free destroys that instance to which a pointed. The value of a is still the same and now points to a memory address where once was an Ta instance.

Solution:

Use FreeAndNil(a) to simultaneously destroy the object to which the variable points to and nillify the variable.

查看更多
Fickle 薄情
3楼-- · 2020-05-05 17:53

An instance method cannot modify the instance variable on which the method was invoked. That's because a method is passed a copy of the instance variable (the implicit Self parameter) rather than being passed a reference to the instance variable.

查看更多
登录 后发表回答