问题
I know that compiler will generate a default constructor if we don't declare it.
And "when" is the point I got confused.
A:
class Base {};
int main()
{
return 0;
}
B:
class Base {};
int main()
{
Base b; // Declare a Base object.
return 0;
}
The A and B difference is only that B declares a real object of Base. At my point, only when we declare a real object and the compiler finds no constructors does it generate a default constructor.
My question is that:
Will code fragment A generate a default constructor of Base?
Does any tool help to check the result? I use Visual Studio 2010, and /d1 reportAllClassLayout seems useless.
回答1:
Quoting C++11.
[class.ctor]§5:
A default constructor for a class
Xis a constructor of classXthat can be called without an argument. If there is no user-declared constructor for classX, a constructor having no parameters is implicitly declared as defaulted (8.4).
[class.ctor]§6:
A default constructor that is defaulted and not defined as deleted is implicitly defined when it is odr-used (3.2) to create an object of its class type (1.8) or when it is explicitly defaulted after its first declaration.
This means that it's declared when your class is defined, and defined (as inline) when it's first used in the given translation unit.
In your case, this means that code fragment A will contain a declaration (but not a definition) of the default constructor, while fragment B will contain both.
回答2:
The declaration of special member functions (default constructors, copy constructor, etc.) always happens as part of the class definition. So both of your examples are the same with regards to Base having a declared default constructor.
A separate question is when a special member function is implicitly defined. This is usually deferred until an actual ODR-use of the member function.
来源:https://stackoverflow.com/questions/19347729/when-does-the-compiler-implicitly-declare-a-default-constructor