[fpc-pascal] dynamic array reference count

Jürgen Hestermann juergen.hestermann at gmx.de
Sat Mar 15 15:20:18 CET 2014


Am 2014-03-15 15:06, schrieb Xiangrong Fang:
 > 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."
-----------




More information about the fpc-pascal mailing list