在TObject和NIL Delphi中再次使用析构函数类

use*_*126 1 memory delphi oop class

可能重复:
TObject和NIL Delphi中的析构函数类

我还有另外一个问题

我有一个班级Ta

当我按下Button1时,它正在执行下一个代码

    var a,b:TA;
begin
    a:=Ta.Create;
    b:=a;
    a.i:=30;

    FreeAndNil(a);

    if (a = NIL) then ShowMessage("a is nil");
    if (b=NIL) then ShowMessage("b is nil");

end;
Run Code Online (Sandbox Code Playgroud)

这两个实例都被破坏了,只有一个是NIL.如何写我知道b是否为空(被破坏).我怎么改变代码,以便它应该写我

a is nil
b is nil
Run Code Online (Sandbox Code Playgroud)

所以我的问题是如何知道指针B的位置是否是一个被破坏的实例

kob*_*bik 6

您可以声明b: Ta absolute a;
这允许您指示编译器将b变量视为存在于同一内存位置,从而有效地将变量叠加在另一个上面.

procedure TForm1.Button1Click(Sender: TObject);
var a: Ta;
    b: Ta absolute a;
begin
  a := Ta.Create;
  b := a;
  a.i := 1;
  FreeAndNil(a);
  if (a = NIL) then ShowMessage('a is nil');
  if (b = NIL) then ShowMessage('b is nil');
end;
Run Code Online (Sandbox Code Playgroud)

这是一篇有用的文章:Absolute(for)初学者.