I have been foolish enough to make a mistake like this:
struct S
{
int[] arr = new int[](5);
}
This is terrible because
S s1;
S s2;
s2.arr[0] = 42;
writeln(s1.arr[0]); // 42 Gotcha!
Of course there are less obvious variants of the same mistake:
import std;
struct S
{
A a = A(5);
}
struct A
{
int[] arr;
this (int l)
{
arr.length = l;
}
}
void main()
{
S s1;
S s2;
s2.a.arr[0] = 42;
writeln(s1.a.arr[0]); // 42 :-(
}
Is there a use case where this makes sense? I would have much appreciated the compiler slapping me on the fingers, but it doesn't. I understand that it is safe and that the compiler can allow this, but why would anyone want that? D-scanner does not check for this either.
I think a helpful error message would be: "Error: The initializer A(5)
allocates memory that is shared among all instances of S
. If you want that, make S.a
static
."
-- Bastiaan.