Doubt about Struct and members

H. S. Teoh hsteoh at qfbox.info
Mon Jan 8 17:56:19 UTC 2024


On Mon, Jan 08, 2024 at 05:28:50PM +0000, matheus via Digitalmars-d-learn wrote:
> Hi,
> 
> I was doing some tests and this code:
> 
> import std;
> 
> struct S{
>     string[] s = ["ABC"];
>     int i = 123;
> }
[...]

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.

However, if you're banking on each instance of S getting its own copy of
the array, you're in for a surprise. In this case, what you want is to
use a ctor to initialize it rather than the above initializer.


T

-- 
Right now I'm having amnesia and deja vu at the same time. I think I've forgotten this before.


More information about the Digitalmars-d-learn mailing list