数组类型分配如何工作的? [英] How array type assignment works?

查看:87
本文介绍了数组类型分配如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的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;

我想知道,如果我从 SwapItemLists 做正确的assingtions。当我分配项目 TMP 什么happends?将创建的产品新副本或将要通过该变量只是指针?

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.

考虑这个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]);

在此code,永远都只有一个阵列。这两个变量 A B 指的是阵列的同一个实例。

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.

字符串实现写入时复制。这意味着,如果一个字符串对象有多个引用,在修改的点是在做一份经参考的结果修改。这有使字符串数据类型的行为像语义值类型的效果。实际上,当您使用字符串赋值,该分​​配是复制语义indistguishable。但是字符串的拷贝的实际执行被延迟直到需要它,作为优化

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆