On Saturday, 14 November 2020 at 23:20:55 UTC, Martin wrote:
Is this intentional?
In the current language design, yes. For the many users who ask
this, no.
All static initializers are run at compile time and refer to the
static data segment - this is consistent across the language.
static x = y; // y is run at compile time
struct A {
int[] a = [1,2,3]; // array built t compile time
}
so.....
void main() {
A a;
a.a[0] = 5;
A b;
b.a[0] == 5; // true!!!
}
Because both actually share the same initial array reference.
And with classes again, same deal. *Constructors* are run for
each instance. But the rest of it is part of the static
initializer that is shared....
IMO this feels not consistent and its weird when a reference
leaks into another instance without having declared it static
member.
Yeah, it is weird and a frequent mistake people make, I almost
wish it had to be more explicit (I'd be sad if it was removed
though, I actually use this in places!).
But once you understand it it kinda makes sense.
Note btw that the reference itself is NOT static... just the
object it refers to. So if you do
obj.a = new Thing
then it doesn't affect other objects, just this one. But they all
start off pointing to the same thing.