Struct bug?

Biotronic simen.kjaras at gmail.com
Mon Oct 2 09:08:59 UTC 2017


On Monday, 2 October 2017 at 08:47:47 UTC, Andrea Fontana wrote:
> Why this code doesn't write two identical lines?
>
> https://dpaste.dzfl.pl/e99aad315a2a
>
> Andrea

A reduced example of where it goes wrong:

class B {}

struct A {
     B b = new B;
}

unittest {
     A a1, a2;
     assert(a1 == a2);
}

In other words, when you initialize the class reference in your 
struct, it has to be a value that's known at compile-time. So the 
compiler creates a single instance of B, and every instance of A 
points to it. So this line:

     A a = A(A(1), 2);

first appends 1 to b.data, then appends 2 to b.data, and it's the 
same b in both cases.

Not knowing what you're attempting to do, I'm not sure how to fix 
your problem. But if what I've described above does indeed cover 
it, initializing b in the constructor is the way to get it to 
work.

--
   Biotronic


More information about the Digitalmars-d-learn mailing list