Home > other >  Using TArray.Copy with generics arrays
Using TArray.Copy with generics arrays

Time:07-29

I'm trying to copy all the items from a generic array to a new one using TArray.Copy (Note: In Delphi XE7 the function has no documentation).

class procedure Copy<T>(const Source, Destination: array of T; SourceIndex, DestIndex, Count: NativeInt); overload; static;
class procedure Copy<T>(const Source, Destination: array of T; Count: NativeInt); overload; static;

The Source array turns into a zero filled array after executing the function:

var
  Source : TArray<Integer>;
  Destination : TArray<Integer>;
begin
  Source := [10, 20];
  SetLength(Destination, Length(Source));

  //here Source is [10, 20]

  TArray.Copy<Integer>(Source, Destination, 0, 0, Length(Source));

  //here Source is [0, 0]
end;

Why is it changing the Source array?

CodePudding user response:

TArray.Copy was broken in XE7 because someone confused the parameters of System.Move:

RSP-9763: TArray.Copy copies from destination to source for unmanaged types

RSP-9887: TArray.Copy is broken in multiple ways

FWIW, for your scenario, it does not need TArray.Copy - System.Copy can handle copying arrays if the copied range starts from the beginning. If you want to copy the entire content, you can even omit the second and third parameter and simply call:

Destination := Copy(Source);
  • Related