c++ - Writing a Default Constructor Forces Zero-Initialization? -
these class definitions:
class foo{ int _ent; public: void printent() const{cout << _ent << ' ';} }; class bar{ foo _foo; public: void printent() const{_foo.printent();} };
and test code:
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();
my output is:
1246382666 1246382666 1246382666
1246382666 0 1246382666
but if add public
default ctor foo
: foo() : _ent(0) {}
my output becomes:
1246382666 1246382666 1246382666
0 0 0
is correct behavior? should adding own default ctor remove possibility of default initialization?
i'm running code on gcc 4.8.1 if matters. results should dependable because i'm running in debug , asserting: assert(sizeof(foo) == sizeof(int) && sizeof(bar) == sizeof(int));
once provide constructor type, invoked, both default initialization , value initialization. it's fundamental principle of language. once define foo::foo()
, called time construct foo
; if there default constructor, invoked, in case of default initialization. behavior seeing correct.
edit:
default initialization explained §8.5/7, in particular:
to default-initialize object of type t means:
— if t (possibly cv-qualified) class type (clause 9), default constructor (12.1) t called [...]
in case, you'll want @ how compiler generates default constructor if none provided, §12.1/4; in particular, generated default constructor invokes default constructor of base classes or members.
value initialization in §8.5/8. default initialization preceded 0 initialization, default initialization doesn't still finds 0 initialized.
more fundamentally, however: in case, fundamental principle of c++ involved, dating long before first standard: if provide constructor object, will used. without doing sorts of strange pointer casts, impossible object without being constructed. standard describes how occurs, , covers lot of other special cases, basic principle has been there start (and proposal cause not respected in standard bound fail).
Comments
Post a Comment