数组类型赋值如何工作? [英] How array type assignment works?
问题描述
我有以下代码:
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;
我想知道我是否正确完成了来自 SwapItemLists
的 assingtions.当我将 Items
分配给 tmp
时会发生什么?将创建 Items
的新副本还是只传递该变量的指针?
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 ?
推荐答案
动态数组是引用类型.这意味着您只是交换了引用.不复制数组的内容.
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.
考虑这个代码:
var
a, b: TArray<Integer>;
....
a := TArray<Integer>.Create(42);
b := a;
b[0] := 666;
Assert(a[0] = 666);
Assert(@a[0] = @b[0]);
在这段代码中,只有一个数组.两个变量 a
和 b
引用该数组的同一个实例.
In this code, there is only ever one array. Both variables a
and b
refer to the same instance of that array.
为了制作动态数组的副本,请使用Copy
函数来自 System
单元.
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.
这篇关于数组类型赋值如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!