cannot take address of scope local in safe function

Paul Backus snarwin at gmail.com
Sun Jun 13 23:22:45 UTC 2021


On Sunday, 13 June 2021 at 17:49:50 UTC, vit wrote:
>
> Is possible create and use scope output range allocated on 
> stack in @safe code?
>
> Example:
> ```d
> //-dip1000
>
>     struct OutputRange{
>         private bool valid = true;
>         private void* ptr;
>     	int count = 0;
>
>         void put(Val)(auto ref scope Val val){
>             assert(this.valid == true);
>         	this.count += 1;
>         }
>
>
>         ~this()scope pure nothrow @safe @nogc{
>         	this.valid = false;
>         }
>
>
>     }
>
>     void main()@safe pure nothrow @nogc{
>         import std.algorithm : copy;
>         import std.range : only;
>
>         scope OutputRange or;
>
>         only(1, 2, 3, 4).copy(&or);   ///Error: cannot take 
> address of `scope` local `or` in `@safe` function `main`
>         assert(or.count == 4);
>     }
>
> ```

Simply remove the `scope` annotation from `or` and from the 
destructor and it works:

https://run.dlang.io/is/hElNYf

Because `OutputRange` is a `struct`, it will still be allocated 
on the stack even if you don't annotate it as `scope`.


More information about the Digitalmars-d-learn mailing list