Passing a reference to a returned reference

Michael michael at toohuman.io
Fri Jul 6 16:14:12 UTC 2018


On Friday, 6 July 2018 at 15:57:27 UTC, Timoses wrote:
> On Friday, 6 July 2018 at 15:33:18 UTC, Michael wrote:
>>
>> This is definitely to do with my use of the setter syntax, 
>> which maybe I am misunderstanding? Because if I change it to a 
>> normal function call like so:
>>
>> a.beliefs(Operator.create());
>>
>> then it complains if I use ref, and doesn't complain if I 
>> don't.
>
> You can try removing the "auto" from the Operator class method
>
> // Error: returning dict escapes a reference to local variable 
> dict
> false
>         static ref create()
>         {
>             double[int] dict;
>             dict[2] = 1.0;
>             dict[1] = 0.0;
>             return dict;
>         }
>
> That indicates that 'dict' is actually returned by value (at 
> least the reference). This sounds a bit confusing.
> AFAIK, in above code a reference 'dict' is created pointing 
> towards memory that stores that dictionary entries. The 
> reference itself is a "pointer"(?) which will "die" when 
> running out of the method's scope. This pointer lives on the 
> function's stack. So returning this "pointer" (essentially a 
> value type, e.g. int) will return it by value.
>
> You could return a reference like so:
>
>     class Operator
>     {
>         static double[int] hdict;
>         static this()
>         {
>              hdict[2] = 1.0;
>              hdict[1] = 0.0;
>         }
>         static ref create()
>         {
>             return hdict;
>         }
>     }
>
> then
>
>> a.beliefs(Operator.create());
>
> should work on the "ref" setter.

Oh of course, as it's a reference type, the "value" being 
returned by 'auto ref' is the value of the reference to the array 
anyway, so I am already passing the reference. Not sure how I 
managed to get really confused about that. Then, forcing the 
function to return a reference to a local reference to a heap 
alloc. array is obviously a problem. This makes way more sense 
now. Thank you again, Timoses, and I hope you enjoyed the result, 
Ali.

I guess I just need to be careful with the setter/getter 
approach, in case I accidentally invoke the getter to return a 
reference, which I then overwrite with another reference. I don't 
know if that's worthy of adding some kind of compiler warning, or 
if I'm just the stupid one to get caught by that, but I'm glad 
it's resolved.

At least it was, technically, working before by leaking access to 
the private member variable and overwriting it.


More information about the Digitalmars-d-learn mailing list