Passing dynamic arrays
Daniel Gibson
metalcaedes at gmail.com
Mon Nov 8 10:04:40 PST 2010
Vladimir Panteleev schrieb:
> On Mon, 08 Nov 2010 19:30:03 +0200, Jens Mueller <jens.k.mueller at gmx.de>
> wrote:
>
>> I find this behavior rather strange. Arrays are neither passed by value
>> (copying the whole array) nor by reference. I see reasons for doing it
>> like this, e.g. doing array = array[1..$] inside should not affect the
>> outside.
>
> Compare to this C-ish program:
>
> void foo(int *array, int length) {
> array = (int*)realloc(array, (length += 1000) * sizeof(int)); // may
> copy the array
> array[0] = 1;
> }
>
> int* a = new int[1];
> foo(a, 1);
> assert(a[0] == 1); // fails if a needs to copied inside foo
>
> C's realloc *may* copy the memory area being reallocated. Just like when
> using realloc, it's something you must be aware of when using D arrays.
>
This might technically be the same thing, but D's nice syntax hides this.
IMHO passing arrays to functions are really inconsistent in D2 anyway:
static arrays are passed by value but dynamic arrays are passed by reference,
but then again, as this thread shows, not really..
And what about associative arrays? (I don't know, haven't tried yet, afaik it isn't documented).
Certainly D's behaviour regarding the dynamic arrays has technical reasons and makes sense when you
know how they're implemented (a fat pointer that is passed by value), but it *feels* inconsistent.
IMHO either all kinds of arrays should *either* be passed by reference (real reference, not
coincidental reference like dynamic arrays are now) *or* by "logical" value, i.e. dynamic arrays
would be dup'ed and associative arrays would be cloned.
BTW: What were the reasons to pass static arrays by value in D2 (while in D1 they're passed by
reference)?
Cheers,
- Daniel
More information about the Digitalmars-d
mailing list