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

Stanislav Blinov stanislav.blinov at gmail.com
Wed Jan 5 05:17:10 UTC 2022


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 :(
> }
> ```
>
> The [spec](https://dlang.org/spec/function.html#ref-functions) 
> states:
>
>> Ref functions allow functions to return by reference, meaning 
>> that the return value must be an lvalue, and the lvalue is 
>> returned, not the rvalue.
>
>
>
> Then why does  the reference to `a` not get returned ?

It is returned. But initializing `c` with it makes a copy. This 
will mutate `a`:

```
func(a) = 10;
```


More information about the Digitalmars-d-learn mailing list