I think that you mean
writeln(foo2.bar); // 3 2 3 4 5
but regardless, it's definitely a bug.
Comment #2 by dsimcha — 2010-06-23T17:45:44Z
Yeah, that's just a typo.
Comment #3 by dsimcha — 2010-06-23T17:46:59Z
Forgot to mention, this also applies to classes, not just structs.
Comment #4 by nfxjfg — 2010-06-24T05:32:46Z
How is this supposed to work "correctly"? Hidden allocation of an array on the heap every time a struct of that type is "constructed"? Disallow initializing non-immutable, non-static array members?
This is not a bug, it's just D _works_. If you assign an array to a global variable, of course it's shared by everyone. Dynamic arrays are reference types. The "variable" being a struct initializer doesn't change this.
I think this really should be marked as INVALID.
(I'm sure it's somewhat confusing for programmers coming from C++ or Java. Especially in Java, the array would be reconstructed every time the constructor is called. Stuff like this _never_ happens in D: structs are always initialized by what boils down to a memcpy.)
Comment #5 by issues.dlang — 2010-06-24T10:07:27Z
bar is a member varible _not_ a class variable and should _not_ be global. As such, two independently constructed variables of type Foo should have bars which referenc totally separate arrays. If bar were static, then they'd be shared, but it's not.
Now, if the second Foo were constructed by copying the first one, then sure, that's going to result in both bars referencing the same array, and setting an element of one will affect the other. However, in this case, both variables of type Foo were constructed independently, so their bars should not point to the same array.
Comment #6 by yebblies — 2010-06-25T01:24:21Z
I can't get dmd to find core.thread atm for some reason, but does the same thing happen with tls globals?
eg.
import core.thread;
import std.stdio;
int[] x = [1, 2, 3];
void main()
{
writeln(x);
x[0] = 9;
writeln(x);
new Thread(&thread2);
}
void thread2()
{
writeln(x);
}
Comment #7 by yebblies — 2012-02-01T19:29:15Z
*** This issue has been marked as a duplicate of issue 2947 ***