Class member initialization with new points to a single instance?

Adam D Ruppe destructionator at gmail.com
Wed Jun 9 18:02:59 UTC 2021


On Wednesday, 9 June 2021 at 17:56:24 UTC, Gregor Mückl wrote:
> class Bar { Foo foo = new Foo(); }

This is a static initialization....

> The assert fails. This is completely surprising to me. Is this 
> actually expected?

Yes, it is expected if you are familiar with the spec.

All member = x things inside a class or struct declaration are 
static initializers. These are CTFE'd into the same form as a 
literal. So there's one instance of Foo there which is assigned 
to the object member before the constructor runs.

For a runtime initialization, you use a constructor.


More information about the Digitalmars-d-learn mailing list