对于类型铸造TArray< X>是安全的到数组X? [英] Is it safe to type-cast TArray<X> to array of X?
问题描述
今天我发现了一个编译器错误( QC#108577 )。
以下程序无法编译:
程序Project1;
{$ APPTYPE CONSOLE}
过程P(M:TArray< TArray< Integer>>
begin
SetLength(M,1,2);
end;
begin
end。
编译器会在 SetLength
说:
[dcc32错误] E2029')'预期但','found
我知道我可以这样修复:
程序P(M:TA rray< TA rray< Integer>>);
var
i:Integer;
begin
SetLength(M,1);
for i:= low(M)to high(M)do
SetLength(M [i],2);
end;
但我自然希望避免使用这个。
以下变体编译并似乎工作:
程序P(M:TArray< TArray< Integer>>);
type
TArrayOfArrayOfInteger =整数数组数组;
begin
SetLength(TArrayOfArrayOfInteger(M),1,2);
end;
我不清楚动态数组的实现细节,
TArray< ;
有没有人知道有足够的话可以说
解决方案编译器内部过程
SetLength
在栈上构建一个维度数组,并为任何动态数组调用DynArraySetLength
,无论是通用还是非。如果通用数组在结构上不能与常规动态数组兼容,则可能不会调用用于设置长度的相同实现。
实际上文档
DynArraySetLength
提供SetLength
作为多维数组的替代。DynArraySetLength
也可以用来代替类型转换,但我没有看到任何理由喜欢一个或另一个。Today I discovered a compiler bug (QC#108577).
The following program fails to compile:
program Project1; {$APPTYPE CONSOLE} procedure P(M: TArray<TArray<Integer>>); begin SetLength(M, 1, 2); end; begin end.
The compiler gags on the
SetLength
line and says:[dcc32 Error] E2029 ')' expected but ',' found
I know I could fix it like this:
procedure P(M: TArray<TArray<Integer>>); var i: Integer; begin SetLength(M, 1); for i := low(M) to high(M) do SetLength(M[i], 2); end;
but naturally I'm keen to avoid having to resort to this.
The following variant compiles and seems to work:
procedure P(M: TArray<TArray<Integer>>); type TArrayOfArrayOfInteger = array of array of Integer; begin SetLength(TArrayOfArrayOfInteger(M), 1, 2); end;
I don't know enough about the implementation details of dynamic arrays,
TArray<T>
casting, reference counting etc. to be confident that this is safe.Is there anybody out there who does know enough to say one way or another whether or not this will produce the correct code at runtime?
解决方案The compiler intrinsic procedure
SetLength
constructs an array of dimensions on the fly on the stack and callsDynArraySetLength
for any dynamic array, be it generic or not. If a generic array wouldn't be structurally compatible with a regular dynamic array, the same implementation for setting the length possibly wouldn't be called.In fact documentation of
DynArraySetLength
offersSetLength
as an alternative for multi-dimensional arrays.DynArraySetLength
could also be used instead of a typecast, but I don't see any reason to prefer one or the other.这篇关于对于类型铸造TArray< X>是安全的到数组X?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!