“何时”编译器是否隐式声明默认构造函数? [英] "When" does the compiler implicitly declare a default constructor?
问题描述
我知道如果不声明编译器,它将生成一个默认的构造函数。
I know that compiler will generate a default constructor if we don't declare it.
when是我感到困惑的地方。
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;
}
A和B的区别仅在于B声明了Base的真实对象。
就我而言,只有当我们声明一个实对象并且编译器没有找到构造函数时,它才会生成默认构造函数。
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.
我的问题是:
-
代码片段A会生成默认的Base构造函数吗?
Will code fragment A generate a default constructor of Base?
是否有任何工具可以帮助您检查结果?我使用Visual Studio 2010,/ d1 reportAllClassLayout似乎没用。
Does any tool help to check the result? I use Visual Studio 2010, and /d1 reportAllClassLayout seems useless.
推荐答案
引用C ++ 11。
[class.ctor]§5
:
类
X
的默认构造函数是类X
的构造函数,无需参数即可调用。如果类X
没有用户声明的构造函数,则将不带参数的构造函数隐式声明为默认值(8.4)。
A default constructor for a class
X
is a constructor of classX
that 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
:
默认的默认构造函数,未默认定义为删除,当它被奇数次使用(3.2)来创建其类类型(1.8)的对象时,会被隐式定义。
这意味着它是在定义和定义您的类时声明的( inline
)在给定的翻译单元中首次使用时。
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.
在您的情况下,这意味着代码片段 A
将包含默认构造函数的声明(而不是定义),而片段 B
将包含两者。
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.
这篇关于“何时”编译器是否隐式声明默认构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!