3

Does copy on write semantics applies for dynamic arrays of records?

How to properly duplicate an array of record?

Is this enough?:

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;

After the copy is complete, I'll need to reset the first array:

SetLength(x, 0);

May I do it this way?

Felippe Tadeu
  • 237
  • 2
  • 11
  • 2
    Your code will work (But I'm sure you have tried it.) so I'm not sure what exactly you are asking. – mg30rg Nov 04 '14 at 12:21
  • Doesn't delphi 6 complain about incompatible types here `b:= x;` since you did not declare like: `x,b: array of recordA;` ? – bummi Nov 04 '14 at 12:44
  • @bummi: Indeed. Both arrays are not the same type, and should not be assignment compatible. – Rudy Velthuis Nov 04 '14 at 15:08

1 Answers1

4

Dynamic arrays do not support Copy-on-Write (CoW) semantics. It does not matter in you example but it matters in other cases.

If you need to copy the contents of a dynamic array use Copy function. Here is an example demonstrating the difference between dynamic array assignment and copying:

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;
kludg
  • 27,213
  • 5
  • 67
  • 118
  • It doesn't matter because of `SetLength(x, 0);` in my code ? – Felippe Tadeu Nov 04 '14 at 13:49
  • That's right, Felippe. There's no reason to make a copy when the original copy is going to be destroyed immediately afterward. It would be more straightforward to construct the array directly in `b`, or to forego `b` and just continue using `x`; you don't need both variables for what amounts to a *single* array. – Rob Kennedy Nov 04 '14 at 15:07
  • @RobKennedy In practice I use that way because there are multiples threads of execution processing the same array. When the worker threads singals the main thread, the main thread duplicates the array (copying it to a buffer) and zero the "main" array to the workers threads fill it again. Because of the thread contention I just serialize the "copy and reset" part. Thus, I need to know about the Copy on Write – Felippe Tadeu Nov 04 '14 at 16:23
  • You could say dynamic arrays support "Copy-on-SetLength". You can even use `SetLength` to set the array to its current length. This will guarantee a unique reference. So it would effectively boil down to a roundabout way of Copying the array. – Disillusioned Nov 04 '14 at 16:59