First Draft: ref For Variable Declarations
Steven Schveighoffer
schveiguy at gmail.com
Mon Apr 15 19:21:55 UTC 2024
On Monday, 15 April 2024 at 17:20:59 UTC, Dennis wrote:
> On Monday, 15 April 2024 at 16:24:51 UTC, Steven Schveighoffer
> wrote:
>> This seems like an unnecessary restriction.
>
> It's necessary to prevent the creation of dangling stack
> pointers, since a `ref` can be bound to a stack variable.
Yes, so you don't allow returning the ref in that case? It is
trivial to know what a `ref` is bound to at compile time.
> When you fix foo's return type to be `ref int`, you get:
>
>> Error: returning `bar(x)` escapes a reference to parameter `x`
Yes, I forgot to update the message after I fixed the return type
in my test, but it compiled for me. I forgot to add `@safe` as
well, I always forget that when testing dip1000.
But also, returning `x` is disallowed in this case.
You also have to add `return` to the parameter, and then it
compiles.
For reference, the edited code which compiles is:
```d
@safe ref int foo(return ref int x)
{
// ref int y = x;
// return y;
// same as:
ref int bar(ref int x2) {
return x2;
}
return bar(x);
}
```
-Steve
More information about the dip.development
mailing list