“何时”编译器是否隐式声明默认构造函数? [英] "When" does the compiler implicitly declare a default constructor?

查看:125
本文介绍了“何时”编译器是否隐式声明默认构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如果不声明编译器,它将生成一个默认的构造函数。

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.

我的问题是:


  1. 代码片段A会生成默认的Base构造函数吗?

  1. 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 class X that can be called without an argument. If there is no user-declared constructor for class X, 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆