Field Initialiser Reused Across Object Instances

Adam thewalker_adam at yahoo.co.uk
Fri Jan 1 13:34:16 UTC 2021


Consider the following:

class A
{
     int x;
}

class B
{
     A a = new A; // I would expect this to be called for each 
"new B".
}

void main()
{
     import std.stdio;

     auto c = new B;
     writeln("c ", c.a.x);
     c.a.x++;
     writeln("c ", c.a.x);
     writeln;

     auto d = new B;
     writeln("d ", d.a.x, " expected 0!");
     d.a.x++;
     writeln("d ", d.a.x, " expected 1!");
}

*** Output ***
c 0
c 1

d 1 expected 0!
d 2 expected 1!

There is only one instance of A in the above program, although I 
would expect one for each instance of B.  The field is not marked 
static.

Is this intended?  My gut reaction is the compiler is memoising 
"new A" because purity is inferred, but doesn't that contradict 
the meaning of "new Class" which should always yield an object 
with it's own identity?

I can fix using a dedicated constructor, but I much prefer 
initializers where possible.



More information about the Digitalmars-d-learn mailing list