why local variables cannot be ref?
H. S. Teoh
hsteoh at quickfur.ath.cx
Mon Nov 25 21:47:48 UTC 2019
On Mon, Nov 25, 2019 at 08:39:08PM +0000, Fanda Vacek via Digitalmars-d-learn wrote:
> On Monday, 25 November 2019 at 08:32:53 UTC, H. S. Teoh 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.
[...]
> void main() @safe
> {
> int a = 1;
> int *b = &a;
> *b = 2;
> assert(a == 2);
> }
>
> does not compile for me with Error: cannot take address of local `a`
> in `@safe` function `main`
>
> so there must be more restrictions in @safe code
Correct, taking the address of a local variable is not allowed because
of the possibility of a dangling pointer if the pointer leaks past the
end of the variable's scope. With -dip1000, though, it should be allowed
as long as you're not leaking the pointer past the lifetime of the
local.
Taking the address of a global is perfectly fine in @safe code, as is
using a pointer to a heap-allocated object (as long as no pointer
arithmetic is involved).
T
--
If you're not part of the solution, you're part of the precipitate.
More information about the Digitalmars-d-learn
mailing list