How does array type assignment work?

I have the following code:

type
  PSuperListItem = ^TSuperListItem;
  TSuperListItem = record
    SubItems  : array of String;
    Marked    : Boolean;
    ImageIndex: Integer;
  end;

  TSuperListItems = array of PSuperListItem;

  TMyList = class(TCustomControl)
  public
   Items, ItemsX : TSuperListItems;
   procedure SwapItemLists;
  end;

procedure TMyList.SwapItemLists;
var tmp:TSuperListItems;
begin
 tmp:=Items; Items:=ItemsX; ItemsX:=tmp;
end;

      

I want to know if I drew the right conclusions from SwapItemLists

. What happens when I assign Items

to tmp

? Will a new copy be created Items

or will only the pointer to this variable be passed?

+3


source to share


1 answer


Dynamic arrays are reference types. This means that you have simply replaced the links. The contents of the arrays are not copied.

The key to answering this question yourself is understanding what it means to be a reference type. In the case of a dynamic array, a variable of the dynamic array type contains a reference to the array. This is implemented behind the scenes with a dynamic array variable that is a pointer to an array.

Consider this code:

var
  a, b: TArray<Integer>;
....
a := TArray<Integer>.Create(42);
b := a;
b[0] := 666;
Assert(a[0] = 666);
Assert(@a[0] = @b[0]);

      



There is only one array in this code. Both variables a

and b

refer to the same instance of this array.

To make a copy of a dynamic array, use the Copy

function from System

.

Other examples of reference types include class instance variables, interface variables, anonymous methods, and strings. They all behave similarly to dynamic arrays, except for strings.

Strings implement copy-on-write. This means that if a string object has more than one reference to it, modifications via the referenced result are copied at the time of modification. This causes the string data type to behave semantically like a value type. In fact, when you use assignment with strings, this assignment is semantically impossible from copying. But the actual implementation of copying the string is deferred until needed, as an optimization.

+8


source







All Articles