写入语义上的复制是否适用于动态记录数组?
如何正确复制记录数组?
这够了吗?:
type
recordA = Record
Y:integer;
end;
var x: array of recordA;
b: array of recordA;
item: recordA;
begin
SetLength(x, 2);
item.Y:= 2;
x[0] := item;
item.Y:= 5;
x[1] := item;
//Copying
b:= x;
复制完成后,我需要重置第一个数组:
SetLength(x, 0);
我可以这样做吗?
答案 0 :(得分:3)
动态数组不支持写时复制(CoW)语义。在你的例子中没关系,但在其他情况下这很重要。
如果需要复制动态数组的内容,请使用Copy
函数。下面是一个演示动态数组赋值和复制之间差异的示例:
procedure TestCopy;
type
recordA = Record
Y:integer;
end;
arrayA = array of recordA;
var x, b, c: arrayA;
item: recordA;
begin
SetLength(x, 2);
item.Y:= 2;
x[0] := item;
item.Y:= 5;
x[1] := item;
b:= x;
x[0].Y:= 4;
Writeln(b[0].Y, ' -- ', x[0].Y);
b:= Copy(x);
x[0].Y:= 8;
Writeln(b[0].Y, ' -- ', x[0].Y);
end;