Classes new'd inside for loop are all the same instance?
lobo via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Sep 8 05:24:48 PDT 2016
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
More information about the Digitalmars-d-learn
mailing list