11
votes

With the latest Delphi version (Berlin/10.1/24), is the [Ref] attribute really necessary?

I ask this because the online doc says:

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.

2
That is, const records <= SizeOf(pointer) are passed by value. If you want to ensure that a reference is passed, use the [ref] attribute.LU RD
ok that sounds very sensible, and makes me think I can give up on using the Ref attribute for const record parameters.user3942667

2 Answers

12
votes

It's pretty much as described by the documentation. You'd use [ref] if you had a reason to enforce the argument to be passed by reference. One example that I can think of is for interop. Imagine you are calling an API function that is defined like this:

typedef struct {
    int foo;
} INFO;

int DoStuff(const INFO *lpInfo);

In Pascal you might wish to import it like this:

type
  TInfo = record
    foo: Integer;
  end;

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

But because TInfo is small, the compiler might choose to pass the structure by value. So you can annotate with [ref] to force the compiler to pass the parameter as a reference.

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

Another example is the new FreeAndNil procedure declaration in Delphi 10.4 in SysUtils.pas, which now finally ensures that only TObject descendants can be used with FreeAndNil. In previous Delphi versions, you could pass anything to this function, even if it didn't make sense.