I have a general question, that may be a little compiler-specific.
I’m interested in the conditions under which a constructor will be called. Specifically, in release mode/builds optimised for speed, will a compiler-generated or empty constructor always be called when you instantiate an 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 this call the generated constructor?
EmptyConstructor* ec = new EmptyConstructor(); //will this call the empty constructor?
InitConstructor* ic = new InitConstructor(); //this will call the defined constructor
EmptyConstructor* ecArray = new EmptyConstructor[100]; //is this any different?
}
I’ve done a lot of searching, and spent some time looking through the generated assembly code in Visual Studio. It can be difficult to follow in release builds though.
In summary:
Is the constructor always called? If so, why?
I understand this will very much depend on the compiler, but surely there’s a common stance. Any examples/sources you can cite would be really appreciated.
When in optimizing mode, if your class or structure is POD (has only POD types) and constructor is not specified, any production quality C++ compiler will not only skip the call to a constructor but not even generate it.
If your class has non-POD members who’s constructor(s) have to be called, compiler will generate default constructor that calls member’s constructors. But even then – it will not initialize POD types. I.e. if you don’t initialize
memberexplicitly, you may end up with garbage there.The whole thing can get even fancies if your compiler/linker has LTO.
Hope it helps! And make your program work first, then use a profiler to detect slow places, then optimize it. Premature optimization may not only make your code unreadable and waste tons of your time, but could also not help at all. You have to know what to optimize first.
Here is a disassembly for code in your example (x86_64, gcc 4.4.5):
As you can see, there are no constructors called at all. There are no classes at all, every object is just a 4 bytes integer.
With MS compiler, YMMV. So you have to check disassembly yourself. But result should be similar.
Good luck!