Static inline field initialization

Moritz Maxeiner via Digitalmars-d digitalmars-d at puremagic.com
Tue Aug 22 05:20:45 PDT 2017


On Tuesday, 22 August 2017 at 11:50:50 UTC, Jonas Mminnberg wrote:
> Because of D's static initialization of members, this assert 
> fails:
>
> class Test {
>     ubyte[] buf = new ubyte[1000];
> }
>
> void main() {
>     auto a = new Test();
>     auto b = new Test();
>     assert(a.buf.ptr != b.buf.ptr);
> }
>
> This is bad, since;
> * It is not how C++ works
> * It introduces silent sharing of data
> * It's usually not what you want
>
> Shouldn't this at least generate a warning, or ideally not be 
> allowed?

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);
}
----

[1] D is not C++ and you shouldn't expect similar looking things 
to behave the same
[2] Compiler warnings are (in my experience) ignored by people, 
anyway
[3] https://dlang.org/spec/class.html#constructors
[4] https://dlang.org/spec/class.html#field-init


More information about the Digitalmars-d mailing list