cannot take address of scope local in safe function

ag0aep6g anonymous at example.com
Sun Jun 13 17:18:46 UTC 2021


On Sunday, 13 June 2021 at 16:27:18 UTC, vit wrote:
> Why I can take address of Foo variable but not Bar?
>
> ```d
> //-dip1000
>
> struct Foo{
>     private double d;
> }
>
> struct Bar{
>     private void* ptr;
> }
>
>
>
> void main()@safe{
>     ///this is OK:
>     {
>         scope Foo x;
>         scope ptr = &x;
>     }
>
>     ///Error: cannot take address of `scope` local `x` in 
> `@safe` function `main`:
>     {
>         scope Bar x;
>         scope ptr = &x;
>     }
> }
> ```

`scope` affects indirections (i.e. pointers). `Foo` doesn't 
contain any indirections, so `scope` doesn't mean anything for 
it. The compiler just ignores it. It's like you wrote `Foo x;` 
without `scope`.

`Bar` does contain an indirection, so `scope` actually matters 
and you get the error.


More information about the Digitalmars-d-learn mailing list