Are empty constructors always called in C++? -
i have general question, may little compiler-specific. i'm interested in conditions under constructor called. specifically, in release mode/builds optimised speed, compiler-generated or empty constructor called when instantiate object?
class noconstructor { int member; }; class emptyconstructor { int member; }; class initconstructor { initconstructor() : member(3) {} int member; }; int main(int argc, _tchar* argv[]) { noconstructor* nc = new noconstructor(); //will call generated constructor? emptyconstructor* ec = new emptyconstructor(); //will call empty constructor? initconstructor* ic = new initconstructor(); //this call defined constructor emptyconstructor* ecarray = new emptyconstructor[100]; //is different? }
i've done lot of searching, , spent time looking through generated assembly code in visual studio. can difficult follow in release builds though.
in summary: constructor called? if so, why?
i understand depend on compiler, surely there's common stance. examples/sources can cite appreciated.
when in optimizing mode, if class or structure pod (has pod types) , constructor not specified, production quality c++ compiler not skip call constructor not generate it.
if class has non-pod members who's constructor(s) have called, compiler generate default constructor calls member's constructors. - not initialize pod types. i.e. if don't initialize member
explicitly, may end garbage there.
the whole thing can fancies if compiler/linker has lto.
hope helps! , make program work first, use profiler detect slow places, optimize it. premature optimization may not make code unreadable , waste tons of time, not @ all. have know optimize first.
here disassembly code in example (x86_64, gcc 4.4.5):
main: subq $8, %rsp movl $4, %edi call _znwm movl $4, %edi movl $0, (%rax) call _znwm movl $4, %edi movl $0, (%rax) call _znwm movl $400, %edi movl $3, (%rax) call _znam xorl %eax, %eax addq $8, %rsp ret
as can see, there no constructors called @ all. there no classes @ all, every object 4 bytes integer.
with ms compiler, ymmv. have check disassembly yourself. result should similar.
good luck!
Comments
Post a Comment