Jens Mueller Wrote:

> Hi,
> 
> I do not understand what's going on behind the scene with this code. Or
> better said I have some idea but maybe I do not see the whole point.
> 
> void foo(int[] array) {
>       array.length += 1000; // may copy the array
>       array[0] = 1;
> }
> 
> auto a = new int[1];
> foo(a);
> assert(a[0] == 1); // fails if a needs to copied inside foo
> 
...
> 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.
> But I wonder whether these semantics are well enough documented?
> I think I should use ref int[] in the example above, shouldn't I?
> 
> Jens

But they are past by reference. You can modify the data all you want, but 
cannot reassign the reference itself. Resizing the array may cause a 
reassignment of that reference. It is not different from the following code 
except resizing does not guarantee a reference change.

import std.stdio;

void assignValue(A a) {
        a = new A();
        a.value = 6;
}
class A {
        int value;
}
void main() {
        A a = new A();
        assignValue(a);
        writeln(a.value);
}

Reply via email to