现在的位置: 首页 > 综合 > 正文

人肉保证,Delphi中的out参数

2013年09月18日 ⁄ 综合 ⁄ 共 571字 ⁄ 字号 评论关闭

Delphi里面,用关键字var或out,可以让函数参数按传递引用,奇怪的是,var和out根本没有本质上的区别,按官方的说法:

An out parameter, like a variable parameter, is passed by reference. With an out parameter, however, the initial value of the referenced variable is discarded by the routine it is passed to. The out parameter is for output only; that is, it tells the function or procedure where to store output, but doesn't provide any input.

看上去,好象是说过程里不能去读out参数的值,因为它的初始值是不可知的,但实际上如果你读了,编译器连个警告都没有,而且out参数也并不是被调用者事先清零(象C#那样),它唯一的用处就是让写过程的程序员警惕一下,这个参数没有什么初始值的,只能给它赋值,而永远不要去用它的值……这一切只能靠程序员人肉保证,编译器一点忙都帮不上。

{ 没有一点警告 }
var

  tmp: Integer;

procedure Foo(out v: Integer);
begin
  tmp := v;
  v := 1;
end;

抱歉!评论已关闭.