Passing dynamic arrays

Jonathan M Davis jmdavisProg at gmx.com
Mon Nov 8 11:51:32 PST 2010


On Monday, November 08, 2010 11:30:33 Daniel Gibson wrote:
> >> So IMHO a compiler warning would  be appropriate in that case.
> >> 
> >> (It would be even better to have more consistent array handling
> >> throughout the different kinds of arrays, as I wrote in another branch
> >> of this thread, but if that is no option, for example because it
> >> contradicts TDPL, a compiler warning is a good compromise)
> > 
> > Honestly, if you want an array that you're passing in to be altered by
> > the function that you're passing it to, it really should be passed by
> > ref anyway.
> 
> 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).

Then the documentation should be updated to be more clear.

> > And if you want to guarantee that it isn't going to be altered, make it
> > const, dup it, or have its individual elements be const or immutable.
> > Problem solved. I really don't see this as an issue. I can understand
> > why there might be some confusion - particularly since the online docs
> > aren't very clear on the matter, but it really isn't complicated, and
> > I'd hate to have to dup an array just to be able to append to it, which
> > is what the warning that you're suggesting would require. A compiler
> > warning is as good as an error really, since you're going to have to fix
> > it anyway, so I'd definitely be against making this either an error or a
> > warning. I see no problem with being allowed to resize arrays that are
> > passed to functions.
> 
> So maybe yet another solution would be to *really* pass dynamic arrays by
> reference (like the doc pretends it's already done)?

That would be a devastating change. It would cause bugs all over the place - 
especially when dealing with std.algorithm. Remember that an array is a range. 
Really, when an array is passed to a function, you're passing a slice of that 
array which happen to slice the whole array.

- Jonathan M Davis


More information about the Digitalmars-d mailing list