'scope' confusion
Paul Backus
snarwin at gmail.com
Fri Apr 15 06:12:06 UTC 2022
On Friday, 15 April 2022 at 05:42:42 UTC, Andy wrote:
> 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;
> }
> ```
No, because `scope` isn't transitive. If the above example were
allowed, then `b.tail.tail` would not be `scope`.
Here's a simplified version, which makes the levels of
indirection more obvious:
```d
@safe @nogc pure nothrow:
void f() {
scope immutable int* a = null;
g(a);
}
void g(scope immutable int* a) {
scope immutable int** b = &a; // error
}
```
> To put it more simply, why doesn't this work?
>
> ```d
> @safe @nogc pure nothrow:
>
> void f() {
> int x = 0;
> scope int* y = &x;
> }
> ```
That example does work. It's only when you get to two levels of
indirection that it fails; for example:
```d
@safe @nogc pure nothrow:
void f() {
int x = 0;
scope int* y = &x;
scope int** z = &y; // error
}
```
More information about the Digitalmars-d
mailing list