Jesse Phillips wrote:
> 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);
> }

I like that explanation. Jonathan is saying the same, I think. I'll
guess my misunderstanding is mainly caused by figuring out that a
reassign is happening and that a reassign to a reference changes the
reference. In C++ you cannot change a reference (I hope I'm right
here.). When using a std::vector one does not need to think about this.
What's the general use of a = new A() in the above code? Where is it
useful?

Jens

Reply via email to