How array type assignment works?

两盒软妹~` 提交于 2019-11-28 14:05:41

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!