Classes new'd inside for loop are all the same instance?
Meta via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Sep 8 05:28:55 PDT 2016
On Thursday, 8 September 2016 at 12:24:48 UTC, lobo wrote:
> I am confused, which is normal, but I'd appreciate some help :-)
>
> If I create N classes in a for loop they are all the same
> instance. I would expect each to be a unique instance of the
> class. See the code below
>
> ---
>
> class C {}
> void main() {
> import std.stdio;
>
> auto c1 = new C();
> writefln("c1:%s", &c1); // OK, instance c1 is unique
>
> auto c2 = new C(); // OK, instance c2 is unqiue
> writefln("c2:%s", &c2);
>
> foreach(a; 0..10) {
>
> C c = new C(); // All instances are the same object
> with the same address?
> writefln("c:%s", &c);
>
> }
> }
> ---
>
> This isn't what I expected. What could I be doing wrong?
>
> Thanks,
> lobo
I don't have time to explain at the moment, but change the `&c`
to `cast(void*)c` and you will see what you expect. I will post
an explanation soon.
More information about the Digitalmars-d-learn
mailing list