Passing and returning arguments by ref

Ali Çehreli acehreli at yahoo.com
Fri Mar 3 18:09:01 UTC 2023


On 3/3/23 06:03, Joe wrote:

 > My understanding was that since A, B and X[] are all reference types,
 > this ought to work, but obviously something is missing.

Think may be due to D not having reference variables. Sometimes one 
needs to use pointers.

I find the following a simpler (and complete ;) ) example. foo() returns 
by ref and indeed, the change made to its return value is visible in main.

However, the same foo() is later called to initialize hopefullyRef but 
not the change made to that variables is not reflected in the array. (By 
the way, the example could be written without an array as well.)

struct S {
     int i;

     void change() {
         ++i;
     }
}

ref S foo(S[] arr) {
     return arr[0];
}

void main() {
     auto arr = [ S(1) ];

     // Ok, this operation changes arr[0]
     foo(arr).change();
     assert(arr[0].i == 2);

     // This one changes the local variable
     auto hopefullyRef = foo(arr);
     hopefullyRef.change();
     assert(hopefullyRef.i == 3);

     // The array is still 2
     assert(arr[0].i == 2);
}

hopefullyRef in just an int. The following definition of the 
hopefullyRef variable would cause the array element be changed:

     // Now an S* (note & on the rigth-hand side)
     auto hopefullyRef = &foo(arr);
     // Now hopefullyRef is an S*, not an S

     // Same as before
     hopefullyRef.change();
     assert(hopefullyRef.i == 3);

     // Now the array is affected (3, not 2)
     assert(arr[0].i == 3);

Ali



More information about the Digitalmars-d-learn mailing list