问题
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've done correctly the assingtions from SwapItemLists
. What happends when I assign Items
to tmp
? Will be created a new copy of Items
or will be passed just the pointer of that variable ?
回答1:
Dynamic arrays are reference types. Which means that you have simply swapped references. The contents of the arrays are not copied.
Key to being able to answer this sort of question yourself is an understanding of what it means to be a reference type. In the case of a dynamic array, the variable of dynamic array type holds a reference to the array. That is implemented behind the scenes by means of the dynamic array variable being a pointer to the 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]);
In this code, there is only ever one array. Both variables a
and b
refer to the same instance of that array.
In order to make a copy of a dynamic array, use the Copy function from the System
unit.
Other examples of reference types include class instance variables, interface variables, anonymous methods and strings. These all behave similarly to dynamic arrays with the exception of strings.
Strings implement copy-on-write. This means that if a string object has more than one reference to it, modifications via a reference result in a copy being made at the point of modification. This has the effect of making the string data type behave semantically like a value type. In effect, when you use assignment with strings, that assignment is semantically indistguishable from copying. But the actual implementation of the copying of the string is postponed until it is needed, as an optimization.
来源:https://stackoverflow.com/questions/27252514/how-array-type-assignment-works