On Monday, 8 January 2024 at 17:56:19 UTC, H. S. Teoh wrote:
...
It's not recommended to use initializers to initialize mutable
array-valued members, because it probably does not do what you
think it does. What the above code does is to store the array
["ABC"] somewhere in the program's pre-initialized data segment
and set s to point to that by default. It does NOT allocated a
new array literal every time you create a new instance of S;
every instance of S will *share* the same array value unless
you reassign it. As such, altering the contents array may
cause the new contents to show up in other instances of S.
This behaviour is generally harmless if your array is
immutable. In fact, it saves space in your executable by
reusing the same data for multiple instances of s. It also
avoids repeated GC allocations at runtime.
...
First of all thanks for replying,
Yes I understood the behavior since I even looked the code
generated: https://godbolt.org/z/xnsbern9f
=]
Maybe my question was poorly written (I'm ESL), but you answered
in the other Topic:
"(Whether the current behaviour should be changed is up for
debate, though. This definitely isn't the first time users have
run into this. In fact just today somebody else asked the same
question on D.learn. So it's definitely in the territory of
"does not do the expected thing", which is an indication that
the default behaviour was poorly chosen.)"
I was in doubt about if this was intended or not... and it seems
the case.
I'm not saying it is wrong by any means, I just found a bit
tricky based on the two ways it could change the value pointed by
the address and/or the address of the member itself.
Again thanks,
Matheus.