why local variables cannot be ref?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Mon Nov 25 09:15:56 UTC 2019


On Monday, November 25, 2019 1:32:53 AM MST H. S. Teoh via Digitalmars-d-
learn wrote:
> On Mon, Nov 25, 2019 at 08:07:50AM +0000, Fanda Vacek via
> Digitalmars-d-learn wrote: [...]
>
> > But anyway, pointers are not allowed in @safe code, so this is not
> > always solution.
>
> [...]
>
> This is incorrect. Pointers *are* allowed in @safe code. Pointer
> *arithmetic* is not allowed.

That and taking the address of a local variable is @system, though with
-dip1000, it becomes @safe by making the result scope, which restricts what
you can do with it. And of course, @trusted can be used where appropriate to
make it so that @system code can be used from @safe code, though obviously,
that means that it's up to the programmer to make sure that they verify that
what the @trusted code is doing is actually @safe.

Further, with regards to taking the address of a local variable being
@system, ref would be @system for exactly the same reasons save for the fact
that there are various restrictions in place to ensure that it can't be used
in a manner which would allow the underlying pointer to exist longer than
the address that it refers to. Allowing variables in general to be declared
as ref instead of only allowing it in restricted circumstances such as
function parameters and return types would put ref in the same @system
quagmire that exists with regards to taking the address of a local variable.
By restricting ref, that problem is avoided, whereas pointers still allow
for full freedom but in return, they require that certain operations that
relate to them be @system (like &, ++, and --).

- Jonathan M Davis





More information about the Digitalmars-d-learn mailing list