Passing a reference to a returned reference

Michael michael at toohuman.io
Fri Jul 6 15:14:01 UTC 2018


On Friday, 6 July 2018 at 14:50:39 UTC, Ali Çehreli wrote:
> On 07/06/2018 07:36 AM, Michael wrote:
> > but not in
> > my case, if this is a weird edge-case with setter member
> functions?
>
> This is all very interesting but I'm dying to see the code. :) 
> Can you change Timoses's code to demonstrate your case?
>
> Ali

I'm just trying to do that now.

Here is what I have in terms of code:

class Agent
{
     private
     {
         double[int] mDict;
     }

     // Setter: copy
     void beliefs(ref double[int] dict)
     {
         import std.stdio : writeln;
         writeln("Setter function.");
         this.mDict = dict;
     }

     // Getter
     auto ref beliefs()
     {
         return this.mDict;
     }
}

class Operator
{
     static auto ref create()
     {
         double[int] dict;
         dict[2] = 1.0;
         dict[1] = 0.0;
         return dict;
     }
}

unittest
{
     import std.stdio : writeln;

     Agent a = new Agent();

     a.beliefs = Operator.create();
     assert(a.beliefs.keys.length == 2);

     writeln(a.beliefs);
}


and here is the output WITH "ref" in beliefs's signature before 
double[int] dict:

➜  dempshaf git:(master) ✗ rdmd -I../ -unittest -main bug_test.d
[2:1, 1:0]

and without "ref":

➜  dempshaf git:(master) ✗ rdmd -I../ -unittest -main bug_test.d
Setter function.
[2:1, 1:0]


I'm surprised it's showing the correct value of the associative 
array, but hopefully this shows my point that it's not printing 
for some reason, when the parameter is ref.


More information about the Digitalmars-d-learn mailing list