Delphi 判断指针为空的函数 Assigned

来源:互联网 发布:linux打开大文件 编辑:程序博客网 时间:2024/04/28 12:41

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;

0 0
原创粉丝点击