const 记录参数的 [Ref] 属性有用吗?

Is the [Ref] attribute for const record parameters useful?

对于最新的Delphi版本(Berlin/10.1/24),[Ref]属性真的有必要吗?

我问这个是因为 online doc 说:

Constant parameters may be passed to the function by value or by reference, depending on the specific compiler used. To force the compiler to pass a constant parameter by reference, you can use the [Ref] decorator with the const keyword.

这与文档中描述的差不多。如果您有理由强制通过引用传递参数,则可以使用 [ref]。我能想到的一个例子是互操作。假设您正在调用一个定义如下的 API 函数:

typedef struct {
    int foo;
} INFO;

int DoStuff(const INFO *lpInfo);

在 Pascal 中,您可能希望像这样导入它:

type
  TInfo = record
    foo: Integer;
  end;

function DoStuff(const Info: TInfo): Integer; cdecl; external libname;

但是因为TInfo很小,编译器可能会选择按值传递结构。所以你可以用[ref]注解强制编译器将参数作为引用传递。

function DoStuff(const [ref] Info: TInfo): Integer; cdecl; external libname;

另一个例子是 Delphi 10.4 中 SysUtils.pas 中新的 FreeAndNil 过程声明,它现在最终确保只有 TObject 后代可以与 FreeAndNil 一起使用。在以前的 Delphi 版本中,您可以将任何内容传递给此函数,即使它没有意义。