Class member always has the same address

Mike Parker via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Mar 19 19:21:51 PDT 2016


On Saturday, 19 March 2016 at 20:24:15 UTC, szymski wrote:

>>class A {
>>	B b = new B();	
>>}

This is *default* initialization, not per instance 
initialization. The compiler will create one instance of B and it 
will become the default initializer of b in *every* instance of 
A. You can verify that with this:

class B {}
class A {
     B b = new B;
}
void main() {
     auto as = [new A, new A, new A];
     assert(as[0].b is as[1].b);
     assert(as[1].b is as[2].b);
     assert(as[0].b is as[2].b);
}

Here, all of the asserts will pass. But add a constructor to A 
that does this:

this() { b = new B; }

And now the first assert will fail. This is *per-instance* 
initialization.




More information about the Digitalmars-d-learn mailing list