Originale-mail to me for new edition

 

Out parameters

 

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.

For example, consider the procedure heading

procedure GetInfo(out Info: SomeRecordType);

When you call GetInfo, you must pass it a variable of type SomeRecordType:

var MyRecord: SomeRecordType;

 ...

GetInfo(MyRecord);

But you’re not using MyRecord to pass any data to the GetInfo procedure; MyRecord is just a container where you want GetInfo to store the information it generates. The call to GetInfo immediately frees the memory used by MyRecord, before program control passes to the procedure.

Out parameters are frequently used with distributed-object models like COM and CORBA. In addition, you should use out parameters when you pass an uninitialized variable to a function or procedure.

 

Topic groups

 

See also

Constant parameters

Parameter semantics: Overview

Value and variable parameters

 

 

译文

 

Out参数

 

一个out参数就象一个变量参数,它传递的也是引用。然而,对于out参数,引用变量的初始值被其传递到的例程丢弃。out参数仅用于输出,也就是说,它告诉函数或过程在哪里存储输出,而不提供任何输入。

例如,对于如下过程首部

procedure GetInfo(out Info: SomeRecordType);

调用GetInfo时,必需向其传递一个类型为SomeRecordType的变量:

var MyRecord: SomeRecordType;

 ...

GetInfo(MyRecord);

但这里不需要用MyRecord传递任何数据到GetInfo过程中;MyRecord只是一个存储GetInfo产生的信息的容器。对GetInfo的调用,会立即释放MyRecord使用的内存(在程序控制传递到过程之前)。

out参数经常用于分布式对象模块,如COMCORBA。此外,向函数或过程传递未初始化的变量时,也可以考虑使用out参数。

 

主题组

 

相关主题

常量参数

参数语义:概述

值参数和变量参数

 

 

编者注

变量参数(var参数)和输出参数(out参数)的共同点在于:传递的都是引用,即不会为变量再分配新的内存。区别在于,var参数对应的变量,其值的改变均来自于程序的执行,即代码编写者对其值具有完整的控制;而out参数对应的变量,在其作为out参数传递给某一例程时,在程序控制交给例程之前,变量占用的内存就被释放了,也就是说,变量的值的改变还受到自动初始化的影响。需要特别注意的是,这里的“释放内存”是指变量中如果含有数据地址指针的情况(如长串、记录类型等),而对于整数、实数等简单类型,则不会有任何操作。有关数据类型和内存管理的更多信息,见数据类型、变量和常量以及内存管理

例如:

procedure TestInteger(out I: Byte);//程序控制交给过程之前不会对out参数I引用的变量有任何操作,因为IByte类型,不占用动态内存。

begin

  I := I + 1;

end;

 

procedure TestString(out S: string);

{程序控制交给过程之前将释放out参数S引用的变量占用的动态内存,因为Sstring类型;释放S的动态数据内存后,S的值为空串。}

begin

end;

 

...

 

var

  V1: Byte;

  V2: string;

begin

  V1 := 2;

  TestInteger(V1);//执行后V1 = 3

  ShowMessage(IntToStr(V1));

  V2 := 'HELLO';

  TestString(V2);//执行后 V2 = '',即空串

  ShowMessage(V2);

end;