Passing dynamic arrays

Jonathan M Davis jmdavisProg at gmx.com
Mon Nov 8 12:24:05 PST 2010


On Monday 08 November 2010 12:07:39 spir wrote:
> On Mon, 08 Nov 2010 20:30:33 +0100
> 
> Daniel Gibson <metalcaedes at gmail.com> wrote:
> > The documentation[1] says: "For dynamic array and object parameters,
> > which are passed by reference, in/out/ref apply only to the reference
> > and not the contents." So, by reading the documentation one would assume
> > that dynamic arrays are passed by reference - *real* reference, implying
> > that any change to the array within the called function will be visible
> > outside of the function.
> > The truth however is that dynamic arrays are not passed by reference and
> > any changes to the length will be lost (even if the arrays data won't be
> > copied).
> 
> Exactly. Pass (and assign) by reference mean different semantics from what
> D does with dyn arrays: that changes are shared.

The reference semantics for Objects and dynamic arrays are identical. They are 
passed by reference, but their reference is passed by value. So, any changes to 
the contents will affect the object or array which was passed in. However, 
changes to the reference (such as assigning a new Object or array or doing any 
operation on an array which would result in reallocation) do not change the 
object or array which was referred to by that reference.

"For dynamic array and object parameters, which are passed by reference, 
in/out/ref apply only to the reference and not the contents." is perfectly 
correct. The problem is whether you read the "which..." as applying to both 
dynamic arrays and object parameters or just object parameters. It's perfectly 
correct as is but apparently ambiguous enough to cause confusion. The docs 
should be updated to be clearer, but the quoted documentation, at least, is 
correct. And there's nothing funny about how arrays work in comparison to 
objects except that arrays happen to have operations which can cause 
reallocation (in addition to new) whereas objects don't.

- Jonathan M Davis


More information about the Digitalmars-d mailing list