First Draft: ref For Variable Declarations

Johan j at j.nl
Sun Apr 14 19:00:21 UTC 2024


On Friday, 12 April 2024 at 20:43:50 UTC, Walter Bright wrote:
> https://github.com/WalterBright/documents/blob/984374ca885e1cb10c2667cf872aebc13b4c1663/varRef.md

It would help if you include an example where such reference 
variable makes the code better / enables writing nicer code. One 
example usecase that I can come up with quickly:

```
struct A {...}

ref A foo();

void bar() {
     A* a = foo(); // not allowed
     A* a = &foo(); // workaround
     a.modifySomething(100);

     A b = foo(); // makes a copy
     b.modifySomething(100); // does not modify the thing returned 
by foo.

     auto c = foo(); // makes a copy

     ref d = foo(); // avoids copy
     d.modifySomething(100); // operates on the thing returned by 
foo
                             // instead of on a copy
}
```
In this case, the reference variable avoids having to use a 
pointer. Not a huge gain, but it helps a little (no need to worry 
about null or about changing the pointer itself).


Another comment: please be exhaustive in examples, in order to 
define clearly and *explicitly* the semantics. Are these allowed 
and if yes what do they do?
```
ref int i = ...
ref j = i;
j = 1; // ?
```

```
void foo(ref int i) {
     ref j = i;
     j = 1; // ?
}
```

```
void foo(ref int i);

ref int j = ...
foo(j); // ?
```

```
int* foo();

ref int i = *foo(); // ?
```

```
ref int i = ...
auto j = i; // typeof(j)?
auto p = &i; // typeof(p)?
```

```
// This is allowed in C++, with different syntax of course.
struct S {
     ref int j;

     S(ref int i) {
         j = i;
     }
     // Default constructor is deleted, because j must be 
initialized.
}

int a;
S aa = S(a);
```

```
(ref int)[3] array_of_refs; // (const int*)[3] arr; is currently 
not allowed, so this case probably neither.
```


More information about the dip.development mailing list