Class member always has the same address
szymski via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun Mar 20 02:53:07 PDT 2016
On Sunday, 20 March 2016 at 02:21:51 UTC, Mike Parker wrote:
> 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.
Ok, I understand now, thanks. I used C# a lot before and there
default initialization worked like per instance initialization.
More information about the Digitalmars-d-learn
mailing list