Sign in Join

Live chat for Free Pascal, Lazarus, Delphi and every Pascal programmer.

Mailing lists / fpc-pascal / 2009-02

dynamic arrays: copy-on-write or not?

2 messages · 2 people ·

Reply by email Subscribe to this list Your subscription

Read-only archive. Use j and k to move between messages.

David Emerson

From the reference guide, december 2008 version:

"Dynamic arrays are reference counted: assignment of one dynamic array-type variable to another will let both variables point to the same array. Contrary to ansistrings, an assignment to an element of one array will be reflected in the other: there is no copy-on-write."

This is fine, but what is strange is that calling setlength DOES perform copy-on-write!

var a, b : array of longint;
begin
  setlength (a,2);
  b := a;
  setlength (a,5);
  writeln (length(b));   // I get 2, not 5
end.

Why this inconsistency? Seems like the behaviors for assigning an element and for using setlength should be similar.

Cheers,
David

Reply by email

Jonas Maebe
to David Emerson
David Emerson wrote 20 lines
"Dynamic arrays are reference counted: assignment of one dynamic array-type variable to another will let both variables point to the same array. Contrary to ansistrings, an assignment to an element of one array will be reflected in the other: there is no copy-on-write." This is fine, but what is strange is that calling setlength DOES perform copy-on-write! var a, b : array of longint; begin setlength (a,2); b := a; setlength (a,5); writeln (length(b)); // I get 2, not 5 end. Why this inconsistency?

It's the way Delphi works. In fact, calling setlength is /the/ way to make a dynamic array unique (afaik, the only alternative is calling copy, but that's slower in case the array already was unique.

Jonas

Reply by email