我可以强制`const`通过引用(也就是`````````参数) [英] Can I force `const` to pass by reference (aka the missing `in` parameter)
问题描述
Delphi有:
var
:通过引用传递;参数是输入和输出。
out
:通过引用传递;参数只能输出。
const
:pass by ..... well it depends;参数只能输入。
in
: pass by reference;参数仅输入,不会更改没有in。
var
: pass by reference; parameter is both input and output.
out
: pass by reference; parameter is output only.
const
: pass by ..... well it depends; parameter is input only.
in
: pass by reference; parameter is input only and will not be changed there is no "in".
我不介意 没有勺子 ,但是我错过了 >;考虑以下代码,是否有更干净的方法?
I don't mind that there is no spoon, but I miss in
; considering the following code, is there a cleaner way of doing this?
type TFastDiv = record
strict private
FBuffer: Int64;
other fields
....
//Must be `var` because `const` would pass a Int64 by value
// |||
// VVV
function DivideFixedI32(var Buffer: Int64; x: integer): integer;
asm
mov r9,rcx
imul dword ptr[rcx] // do stuff with the buffer
..
mov ecx, [r9+4] // do other stuff with the rest of the buffer
{将代码更改为 imul ecx; ...; shr r9,32; mov ecx,r9d
将允许通过值,但让我们假设代码不能更改。} / sub>
{Changing the code to imul ecx;...;shr r9,32;mov ecx,r9d
would allow pass by value, but let's assume the code must not be changed.}
class operator TFastDiv.IntDivide(x:integer; const buffer:TFastDiv):integer;
begin
Result:= DivideFixedI32(Int64((@buffer.FBuffer)^), abs(x)); <<-- Ugly
if (x < 0) then Result:= - Result;
end;
DivideFixed
永远不会更改缓冲区。例程的全部要点是缓冲区
是一个预先计算的值,不会更改。
DivideFixed
will never change the buffer. The whole point of the routine is that buffer
is a precalculated value that does not change.
在类运算符我将缓冲区声明为const,因为记录不能更改。
In the class operator I declare buffer as const, because the record must not change.
问题是:
如果我坚持声明缓冲区
参数IntDivide 作为 const
是一种更干净的编码方式,或者我卡在pointer_to / points_to黑客
The question is:
If I insist on declaring the buffer
parameter in IntDivide
as const
is there a cleaner way of coding or am I stuck in the pointer_to/points_to hack?
推荐答案
较新的编译器版本支持 [Ref]
decorator: p>
Newer compiler versions support the [Ref]
decorator:
procedure Foo(const [Ref] Arg1: Integer; [Ref] const Arg2: Byte);
从文档,其中强调 [Ref]
可以在之前或之后 const
关键字。
Example adapted from the documentation, which emphasises the [Ref]
can go either before or after the const
keyword.
这篇关于我可以强制`const`通过引用(也就是`````````参数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!