'scope' confusion

Dukc ajieskola at gmail.com
Fri Apr 8 07:02:57 UTC 2022


On Friday, 8 April 2022 at 05:52:09 UTC, Andy wrote:
> In the following code, I can pass a non-`scope` argument to a 
> function expecting a `scope` parameter, but I can't pass a 
> `scope` argument. That seems backwards?

I was already writing "these both should pass", but then I 
noticed what's wrong.

The scope at `f` means you cannot escape the outer array. But on 
`yesScope`, it means that you cannot escape the strings! In other 
words, this fails for the same reason that this would fail:

```
@safe void main()
{ scope immutable(char)[] a = "one";
   scope immutable(char)[] b = "two";
   auto array = [a, b];
}
```

It fails, because D does not have a concept of an array holding 
scope variables (or a pointer pointing to a scope variable). Only 
the outernmost array or pointer can be `scope`. That's with 
dynamic arrays.

However, with static arrays and structs, `scope` means that each 
member of them is `scope`. Nothing else would make sense, because 
these contain their data in the variable itself. Assign a static 
array or a struct to new one, and it's contents becomes and 
independent copies of the original. Data escaping them is no more 
issue than `5` escaping an `int`.


More information about the Digitalmars-d mailing list