Schreiben eines Standardkonstruktors erzwingt die Nullinitialisierung?
Das sind meine Klassendefinitionen:
class Foo{
int _ent;
public:
void printEnt() const{cout << _ent << ' ';}
};
class Bar{
Foo _foo;
public:
void printEnt() const{_foo.printEnt();}
};
Und das ist mein Testcode:
char* buf = new char[sizeof(Foo) + sizeof(Foo) + sizeof(Bar)];
fill(buf, buf + sizeof(Foo) + sizeof(Foo) + sizeof(Bar), 'J');
cout << ((int*)buf)[0] << ' ' << ((int*)buf)[1] << ' ' << ((int*)buf)[2] << endl;
Foo* first = new (buf) Foo;
Foo* second = new (buf + sizeof(Foo)) Foo();
Bar* third = new (buf + sizeof(Foo) * 2) Bar;
first->printEnt(); second->printEnt(); third->printEnt();
Meine Ausgabe ist:
1246382666 1246382666 1246382666
1246382666 0 1246382666
Aber wenn ich ein @ hinzufüpublic
default ctor toFoo
: Foo() : _ent(0) {}
Meine Ausgabe wird zu:
1246382666 1246382666 1246382666
0 0 0
Ist das richtig? Sollte das Hinzufügen meiner eigenen Standard-Ctor die Möglichkeit der Standard-Initialisierung entfernen?
Ich führe diesen Code auf gcc 4.8.1 aus, wenn es darauf ankommt. Die Ergebnisse sollten zuverlässig sein, da ich im Debugging- und Asserting-Modus bin:assert(sizeof(Foo) == sizeof(int) && sizeof(Bar) == sizeof(int));