Please fix `.init` property

H. S. Teoh hsteoh at qfbox.info
Mon Jan 8 18:07:19 UTC 2024


On Sun, Jan 07, 2024 at 11:12:30PM +0000, Hipreme via Digitalmars-d wrote:
> I was doing a completely functional code, then I noticed some variable
> changing abruptly to a strange value. After the first run in a
> function, the value completely changed, I've reduced and found that I
> was able to actually modify `.init`.
> 
> ```d
> struct MyTest
> {
>     string[] dirs = ["source"];
> }

Using initializer syntax to initialize mutable array members is
generally not recommended, because it does not do what you expect. It
does NOT allocate a new array per instance of MyTest; instead, it stores
the array once in the program's preinit data segment, and sets the
default value of .dirs to point to that instance.  This is generally
harmless if the array is immutable, but if the data is mutable, you're
probably in for a surprise.

If you want every instance of the struct to have a fresh copy of the
array, use a ctor instead.

(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.)


T

-- 
If blunt statements had a point, they wouldn't be blunt...


More information about the Digitalmars-d mailing list