[fpc-pascal] Dynamic arrays, yet another pitfall

Jürgen Hestermann juergen.hestermann at gmx.de
Sat Feb 15 19:20:28 CET 2014


Am 2014-02-09 19:29, schrieb Florian Klämpfl:
 > Am 09.02.2014 18:41, schrieb Jürgen Hestermann:
 >> So it seems there is a copy-on-write *but* only when using SetLength.
 > No. There is no COW, only ref. counting. SetLength just forces an unique
 > instance of the array if needed.

But this *is* Copy-On-Write! When I set the length it is not different to changing elements.
In both cases I write to the array (modify it).
But suddenly I have a duplicate.
I would not expect such a behaviour as I don't get a dublicate when changing elements either.



 >> What a very consistent design!
 > There is a very good reason for this design: speed. COW would mean that
 > at every write to a dyn. array element, ref. count must be checked. This
 > would render dyn. arrays useless for a lot of applications due to poor
 > speed. So dyn. arrays with COW simply make no sense.

Yes. Therefore I was expecting that *never* a copy is made.
While Ansistrings *do* have COW dynamic arrays do *not* have it.
If that would be true then variables pointing to the same dynamic
array should do this forever (unless the programmer assigns a new array with := ).
Setlength should *not* be considered different to modifying elements.
For what reason? Both are writes to the array.

As this seems not to be true it should be mentinoned in the documentation with big exclamation marks!!
Otherwise *everybody* who is using dynamic arrays for the first time will assume Setlength beeing
treated the same as element changes. Why should someone consider these things as different?
This is a source of errors and a huge confusion as discussed here too:
http://www.delphitools.info/2011/06/15/poll-dynamic-arrays-as-reference-or-value-type



More information about the fpc-pascal mailing list