Classes new'd inside for loop are all the same instance?

rikki cattermole via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Sep 8 05:30:00 PDT 2016


On 09/09/2016 12:24 AM, 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

Well for starters C is already a pointer ;)
cast(void*) should do the trick not &.



More information about the Digitalmars-d-learn mailing list