关于delphi Assigned

1. 根据 Delphi 指令参考手册中

说明: 
Assigned 函式在参数不为 nil 时传回 True, 表示指针已经指到某个内存地址,这个内存地址可能是一个对象地首地址,也可能在函数或过程中,声明一个指针变量,没有赋值为 nil ,无乱的指向某处,这两个种情况, Assigned (指针变量)都不为 nil , 函数放回 True ;

而参数为 nil 时则传回 False 。


Assigned 并不是一个真正的函数。

技巧: 
用呼叫 Assigned 的方式来取代直接把参数拿来和 nil 比较,效率会更好。

2. 这个问题要从内存方面来解释 
当你建构一个物件 SomeComponet.Create(Owner);
系统会有一个指针指向这个对象 
当你解构一个物件 SomeComponet.Free;
系统会将指针指到的东西杀掉,但是指标还是指在相同的位置 
请注意计算机的资源是有限的, 
所以可能下一步你的程序要跟系统要资源, 
刚才的指针位置,就出现了其它的数据 
If Assigned(SomeComponet) then SomeComponet := nil;
先检查这个对象有没有在其它地方被设成 nil , 
然后再将它设成 nil 。

当我们无法预测使用者会如何操爆他的计算机, 
程序员必须留意内存的管理。 小弟浅见 ...


3
function Assigned(var P): Boolean;

Description

Use Assigned to determine whether the pointer or procedure referenced by P is nil. P must be a variable reference of a pointer or procedural type. Assigned(P) corresponds to the test P<> nil for a pointer variable, and @P <> nil for a procedural variable.

Assigned returns False if P is nil, True otherwise.

检查指针指向的参考变量或过程是否为 nil

每次我通常的处理方法都是:

if assigned(frm) then frm.close; 但是当下次调用时就会出错。为什么呢,直到咋天我才知道原因

frm.close;frm.free; 只是指定这块内存可以重写,并未释放为 NIL 因此当下次调用时即使 frm.free 已经

执行过 assigned(frm) 仍为 TRUE ,再次释放 frm.Close 或者 frm.free 肯定会报错;应为 frm.Close 或 frm.free 是释放 对象指针 frm 指向的内存空间,在上次已经释放调了,但是 frm 本身并没有 初始化为 nil , 相反它还是指向被释放的内存地址;东西已经没有了,没有地东西去释放,不报错错才怪。

正确的处理方法:

if assigned(frm) then 
begin
frm.close;
frm:=nil;
end;

或 :

if assigned(frm) then 
begin
frm.close;
freeandnil(frm);
end;

// 可以测试一些就能真正理解 FreeAndNil 和 Assigned 函数地使用方法了;

procedure FreeAndNil(var Obj);

Description

Use FreeAndNil to ensure that a variable is nil after you free the object it references. Pass any variable that represents an object as the Obj parameter.

var P: Pointer;

begin
P := nil;
if Assigned (P) then Writeln ('You won''t see this');
GetMem(P, 1024); {P valid}
FreeMem(P, 1024); {P no longer valid and still not nil}
if Assigned (P) then Writeln ('You''ll see this');
end;

参考:http://www.cppblog.com/sleepwom/archive/2010/08/20/124086.html

原文地址:https://www.cnblogs.com/findumars/p/4278140.html