[Issue 22270] [DIP1000] class does infer scope in methods when assigned to a scope variable

d-bugmail at puremagic.com d-bugmail at puremagic.com
Fri Sep 3 22:45:54 UTC 2021


--- Comment #8 from Dennis <dkorpel at live.nl> ---
(In reply to João Lourenço from comment #7)
> I was referring to:
> ```
> scope bar1 = Bar();
> auto  bar2 = Bar();
> ```
> I thought `scope` only meant instantiating on the stack when used this way.
> But I guess it also marks all fields as scope.

Scope *only* applies to the fields, there's nothing else it can apply to
because a struct is a value type. A `struct S {int* x;}` is just an `int* x`.
Both variables bar1 and bar2 are each just 16 bytes on the stack: the memory
needed for the single int[] variable that is Bar's member (assuming a 64-bit

When you take the address of a local variable `&bar1` or `&bar2`, then the
resulting pointer necessarily needs to be `scope` since it points to stack
memory, but this is something the compiler does based on its knowledge of where
variables are declared, this is *not* what `scope` does in `scope bar1 =
Bar();`. That declares the `int[]` member scope, which is why you can't take
the address of `bar1`, since then you need a scope pointer to a scope array.

> If I understood correctly,
> the instance `bar1` lifetime is the current scope and so are all its
> members, and the instance `bar2` lifetime is the current scope but its
> members are assumed to have infinite lifetime.

I think your confusion comes from the fact you think `scope` applies to the
variable declaration, so you can have a `scope int` and then if you take the
address of that you get a scope pointer. That's not an unreasonable thing to
think, it's just not how it is designed in D. A `scope int` does nothing, a
`scope int*` applies to the indirection.


More information about the Digitalmars-d-bugs mailing list