cannot take address of scope local in safe function
vit
vit at vit.vit
Sun Jun 13 17:49:50 UTC 2021
On Sunday, 13 June 2021 at 17:18:46 UTC, ag0aep6g wrote:
> 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.
Thanks.
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);
}
```
More information about the Digitalmars-d-learn
mailing list