On Tuesday, 22 August 2017 at 12:38:50 UTC, Jonas Mminnberg wrote:
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,

While I can understand the sentiment, there is a difference between sharing data between threads and sharing data between class instances in the same thread, the latter of which is occurring here. There is a bug with static field initializers (as others have pointed out), but it's about the fact that the array is stored in global storage and not in TLS and doesn't apply in the example above.

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.

While I don't find how it works surprising personally (it's consistent with how static initialization works everywhere else in D) - in contrast to other subtleties in D - it might make be sensible to include this in the Dlang tour.

Reply via email to