On Friday, 10 June 2022 at 07:49:43 UTC, Mike Parker wrote:
...
And it *is* documented:
Struct fields are by default initialized to whatever the
Initializer for the field is, and if none is supplied, to the
default initializer for the field's type.
The default initializers are evaluated at compile time.
https://dlang.org/spec/struct.html#default_struct_init
Hmm I understand the text but for this intializers I was
expecting new address with length 5, for example:
import std.stdio;
struct S{
int[] arr = new int[](5);
int[2] arr2;
}
void main(){
S s1, s2;
s2.arr[0] = 42;
writeln(s1.arr[0], " address: ", &s1.arr[0]);
writeln(s2.arr[0], " address: ", &s2.arr[0]);
s2.arr2[0] = 10;
writeln(s1.arr2[0], " address: ", &s1.arr2[0]);
writeln(s2.arr2[0], " address: ", &s2.arr2[0]);
}
Prints:
42 address: 5586F5BD9CC0
42 address: 5586F5BD9CC0
0 address: 7FFFC65C7A20
10 address: 7FFFC65C7A40
And as it can be seen: s1.arr and s2.arr shares the same address.
So, in the case of "int[] arr = new int[](5)", an array of length
5 of type int will be instantiated and its address will be shared
among whoever instantiates "S" and be pointed and accessed
through arr.
In the second case, "int[2] arr2", 2 consecutive integer spaces
in memory will be allocate independently for each "instantiation"
of "S", so different address.
I never saw this before (I mean I never wrote the first case),
I'm used to the "int[2] arr2;" way of declaring it, but if I had
looked this code without knowing this, I'd be certain that s1.arr
and s2.arr would have different addresses.
This is a bit weird (At least for a newbie like me), I really
think the compiler should emit an warning about this.
Matheus.