'scope' confusion

Andy andy.pj.hanson at gmail.com
Fri Apr 15 05:42:42 UTC 2022


On Friday, 8 April 2022 at 07:02:57 UTC, Dukc wrote:
> 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`.

Is there any way to do this safely?

```
@safe @nogc pure nothrow:

void f() {
	scope immutable Node a = Node(1, null);
	g(a);
}

void g(scope immutable Node a) {
	scope immutable Node b = Node(2, &a);
}

struct Node {
	immutable int head;
	immutable Node* tail;
}
```

I would think that getting `&a` in that context ought to be safe 
because it's only used in a `scope` variable, but apparently not.
I'm using `immnutable` here because I know `a.tail = b` would be 
wrong; they're both `scope` but `a` is a parameter and thus 
outlives `b`.

To put it more simply, why doesn't this work?

```
@safe @nogc pure nothrow:

void f() {
	int x = 0;
	scope int* y = &x;
}
```


More information about the Digitalmars-d mailing list