Sign in Join

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

Mailing lists / fpc-pascal / 2014-03

dynamic array reference count

5 messages · 4 people · –

Reply by email Subscribe to this list Your subscription

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

Xiangrong Fang

Hi there,

I just want to confirm one thing:

var
  a, b: array of Integer;
begin
  SetLength(a, 100);
  SetLength(b, 100);
  a := b;
end.

Now "a" will point to the same memory block as "b". Since dynamic arrays are ref counted, I don't need to worry about the memory originally allocated for "a", right?

Thanks,
Xiangrong

Reply by email

Jürgen Hestermann
to Xiangrong Fang
Xiangrong Fang wrote 10 lines
I just want to confirm one thing: var a, b: array of Integer; begin SetLength(a, 100); SetLength(b, 100); a := b; end. Now "a" will point to the same memory block as "b". Since dynamic arrays are ref counted, I don't need to worry about the memory originally allocated for "a", right?

Yes, you don't need to worry about the old array.

But there other peculiarities of dynamic arrays which are very inportant to know IMO. There was a larger discussion about them recently. I added some more information to http://wiki.freepascal.org/Dynamic_array because some very important details about dynamic arrays were not mentioned in any documentation.

I added the last sentence which may help you to avoid false assumptions:

-----------
Although writing to elements of dynamic arrays does not create a new instance of the array (no copy-on-write as it exists for Ansistrings) using SetLength on such arrays does create a copy! So if 2 dynamic array variables point to the same array (one has been assigned to the other) they do not do so after having used SetLength on one of them (or on both). Afterwards both variables are separated arrays each with elements independend from the other array."
-----------

Reply by email

Michael Schnell
to Jürgen Hestermann: Yes, you don't need to worry about the old array. But there other peculiarities of…
Jürgen Hestermann wrote
I added the last sentence which may help you to avoid false assumptions:

Well done !

OTHO, IMHO this perfectly documents that the decision (supposedly by Borland) ) to do it this way is a very nasty and the conceptional difference between Strings and dynamic arrays, that both use reference counting and "SetLength" is not really easy to be communicated to the users code programmers. (Even though it might be possible to do nice tricks with them when you exactly know what you are doing.)

-Michael

Reply by email