Returning value by ref does not create a ref. Is this intentional?

Tejas notrealemail at gmail.com
Wed Jan 5 05:38:45 UTC 2022


On Wednesday, 5 January 2022 at 05:15:30 UTC, Paul Backus wrote:
> On Wednesday, 5 January 2022 at 04:35:12 UTC, Tejas wrote:
>> ```d
>> import std.stdio:writeln;
>>
>> ref int func(return ref int a){
>>     a = 6; // modifies a as expected
>>     return a;
>> }
>> void main(){
>>     int a = 5;
>>     auto c = func(a); // I expected c to alias a here
>>     c = 10; // Expected to modify a as well
>>     writeln(a); // prints 6 :(
>> }
>> ```
>
> Local variables cannot be references, so when you assign the 
> reference returned from `func` to the variable `auto c`, a copy 
> is created.
>
> To make this work the way you want it to, you must use a 
> pointer:
>
> ```d
> int a = 5;
> auto p = &func(a); // use & to get a pointer
> *p = 10;
> writeln(a); // prints 10
> ```

The entire reason I wanted to get a `ref` was so that I can avoid 
the `*` :(
Didn't know you could take the address of a function _invocation_ 
though, so asking this wasn't completely redundant

Thank you :D

Guess I'll be stuck with ol' `struct Ref(T){...}`


More information about the Digitalmars-d-learn mailing list