为什么即使在调用 .Free 之后也会分配 Delphi 对象? [英] Why are Delphi objects assigned even after calling .Free?

查看:18
本文介绍了为什么即使在调用 .Free 之后也会分配 Delphi 对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Delphi中,为什么我调用析构函数后,Assigned()函数仍然返回True?

In Delp why does the Assigned() function still return True after I call the destructor?

下面的示例代码将向控制台写入sl 仍然被分配".

The below example code will write "sl is still assigned" to the console.

不过,我可以调用 FreeAndNil(sl);它不会被分配.

However, I can call FreeAndNil(sl); and it won't be assigned.

我用 Delphi 编程有一段时间了,但这对我来说从来没有意义.

I've been programming in Delphi for a while, but this never made sense to me.

谁能解释一下?

program Project1;
{$APPTYPE CONSOLE}
uses SysUtils, Classes;

var
  sl : TStringList;

begin
  sl := TStringList.Create;
  sl.Free;
  if Assigned(sl) then
    WriteLn('sl is still assigned')
  else
    WriteLn('sl is not assigned');
end.

我尝试比较 VCL 操作...... FreeAndNil 简短而甜蜜,而且很有意义:

I tried comparing the VCL operations... FreeAndNil is short and sweet and makes sense:

procedure FreeAndNil(var Obj);
var
  P: TObject;
begin
  P := TObject(Obj);
  TObject(Obj) := nil;  // clear the reference before destroying the object
  P.Free;
end;

但是 TObject.Free 是在神秘的汇编程序中,我不明白:

But TObject.Free is in mysterious assembler, which I don't understand:

procedure TObject.Free;
asm
        TEST    EAX,EAX
        JE      @@exit
        MOV     ECX,[EAX]
        MOV     DL,1
        CALL    dword ptr [ECX].vmtDestroy
@@exit:
end;

推荐答案

如果使用 sl.Free,对象被释放,但变量 sl 仍然指向现在无效的内存.

If you use sl.Free, the object is freed but the variable sl still points to the now invalid memory.

使用 FreeAndNil(sl) 来释放对象和清除指针.

Use FreeAndNil(sl) to both free the object and clear the pointer.

顺便说一句,如果你这样做:

By the way, if you do:

var
  sl1, sl2: TStringList;
begin
  sl1 := TStringList.Create;
  sl2 := sl1;
  FreeAndNil(sl1);
  // sl2 is still assigned and must be cleared separately (not with FreeAndNil because it points to the already freed object.)
end;




procedure TObject.Free;
asm
    TEST    EAX,EAX
    JE      @@exit              // Jump to exit if pointer is nil.
    MOV     ECX,[EAX]           
    MOV     DL,1
    CALL    dword ptr [ECX].vmtDestroy  // Call cleanup code (and destructor).
@@exit:
end;

这篇关于为什么即使在调用 .Free 之后也会分配 Delphi 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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