Destructor类在TObject和NIL Delphi中 [英] Destructor class in TObject and NIL Delphi

查看:207
本文介绍了Destructor类在TObject和NIL Delphi中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么在我调用 Free 方法之后,对象不是 nil

我的意思是下一个类:

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;

我的问题是为什么释放对象不是 nil 如何在析构函数之后使 a 成为 nil 而不使用 a: = nil

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?

推荐答案

说明:

变量 a 只有在被赋值时才成为 nil / strong> nil 。这意味着需要在代码中存在 a:= nil ,现在缺少。

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.

免费是>只是一个方法,处理 Ta 类的实例。免费销毁 a 指向的实例。 a 仍然相同,现在指向一个内存地址,其中曾经是 Ta 实例

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.

解决方案:

使用 FreeAndNil(a)同时破坏变量指向的对象,并使变量变为nillify。

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

这篇关于Destructor类在TObject和NIL Delphi中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆