为什么const记录参数按值传递?
Why are const record parameters passed by value?
如果我有记录,例如
type
TMyRec = record
x : string;
end;
还有一个procedure test(const x : TMyRec);
。为什么该参数按值传递(即传入副本)而不是按引用传递。我本以为从效率的角度来看,它应该通过引用传递(比如整数)。
看来这和记录的大小有关,因为
procedure test(const x : TMyRec);
类型
type
TMyRec = record
x : Array[1..4] of byte;
end;
会按值传递,
type
TMyRec = record
x : Array[1..5] of byte
end;
将在 32 位上通过引用传递,对于 64 位我们需要一个 9 字节的记录以在东京(10.2.3)或更早版本上通过引用传递,里约热内卢(10.3)在两个 32 位上的行为相同和 64 位。感谢所有对我的问题发表评论并提供额外信息的人 references/suggestions.
参见东京文档 here。特别是
Value and constant (const) parameters are passed by value or by reference, depending on the type and size of the parameter:
...
Sets, records, and static arrays of 1, 2, or 4 bytes are passed as
8-bit, 16-bit, and 32bit values. Larger sets, records, and static
arrays are passed as 32-bit pointers to the value. An exception to
this rule is that records are always passed directly on the stack
under the cdecl, stdcall, and safecall conventions; the size of a
record passed this way is rounded upward to the nearest double-word
boundary.
如果你想强制传递引用,你可以将你的参数声明为const [ref]
,像这样:
procedure test(const [ref] x : TMyRec);
如果我有记录,例如
type
TMyRec = record
x : string;
end;
还有一个procedure test(const x : TMyRec);
。为什么该参数按值传递(即传入副本)而不是按引用传递。我本以为从效率的角度来看,它应该通过引用传递(比如整数)。
看来这和记录的大小有关,因为
procedure test(const x : TMyRec);
类型
type
TMyRec = record
x : Array[1..4] of byte;
end;
会按值传递,
type
TMyRec = record
x : Array[1..5] of byte
end;
将在 32 位上通过引用传递,对于 64 位我们需要一个 9 字节的记录以在东京(10.2.3)或更早版本上通过引用传递,里约热内卢(10.3)在两个 32 位上的行为相同和 64 位。感谢所有对我的问题发表评论并提供额外信息的人 references/suggestions.
参见东京文档 here。特别是
Value and constant (const) parameters are passed by value or by reference, depending on the type and size of the parameter:
...
Sets, records, and static arrays of 1, 2, or 4 bytes are passed as 8-bit, 16-bit, and 32bit values. Larger sets, records, and static arrays are passed as 32-bit pointers to the value. An exception to this rule is that records are always passed directly on the stack under the cdecl, stdcall, and safecall conventions; the size of a record passed this way is rounded upward to the nearest double-word boundary.
如果你想强制传递引用,你可以将你的参数声明为const [ref]
,像这样:
procedure test(const [ref] x : TMyRec);