November 25, 2019 Re: why local variables cannot be ref? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Dukc | On Monday, 25 November 2019 at 09:00:49 UTC, Dukc wrote:
> On Monday, 25 November 2019 at 03:07:08 UTC, Fanda Vacek wrote:
>> Is this preferred design pattern?
>>
>> ```
>> int main()
>> {
>> int a = 1;
>> //ref int b = a; // Error: variable `tst_ref.main.b` only parameters or `foreach` declarations can be `ref`
>> ref int b() { return a; }
>> b = 2;
>> assert(a == 2);
>> return 0;
>> }
>> ```
>>
>> Fanda
>
> It's okay, but I'd prefer an alias, because your snippet uses the heap needlessly (it puts variable a into heap to make sure there will be no stack corruption if you pass a pointer to function b() outside the main() function)
Yes alias can help, but my original need was like
void main() @safe
{
int[] a = [1, 2];
alias head = a[0];
head = 2;
assert(a[0] == 2);
}
there the alias doesn't work
Fanda
|
November 25, 2019 Re: why local variables cannot be ref? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Fanda Vacek | 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. |
Copyright © 1999-2021 by the D Language Foundation