Static inline field initialization

Jonas Mminnberg via Digitalmars-d digitalmars-d at puremagic.com
Tue Aug 22 05:38:50 PDT 2017


On Tuesday, 22 August 2017 at 12:20:45 UTC, Moritz Maxeiner wrote:

>
> I agree that it can be confusing if you try to read it with C++ 
> semantics [1]; the solution, however, imho is not to change D 
> semantics or throw warnings [2], but to refer to the D spec 
> [3], which states that static initialization of class members 
> is used instead of default initialization (before any 
> constructors are run). To me that means a statically 
> initialized class field shall have the same value in all class 
> instances, i.e. it's not silent sharing, you explicitly 
> requested the sharing. If that doesn't mean the same to others, 
> the D spec wording should be updated to be clearer on the 
> subject.
> If you don't want instances to share a field value, instead of 
> static initialization you can use constructor initialization 
> [4]:
>
> ----
> class Test
> {
>     ubyte[] buf;
>     this()
>     {
>         buf = new ubyte[1000];
>     }
>  }
>
> void main()
> {
>     auto a = new Test();
>     auto b = new Test();
>     assert(a.buf.ptr != b.buf.ptr);
> }

I know that it is according to the standard but since D has gone 
out of it's way to make sure sharing doesn't occur otherwise, by 
defaulting to TLS storage etc, I feel this breaks the "no 
surprises" rule. I took me a long time to find this out and when 
I mentioned it to other casual D programmers they also had no 
idea this was how it worked.





More information about the Digitalmars-d mailing list