C++ 中是否有隐式默认构造函数? [英] Is there an implicit default constructor in C++?

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

问题描述

在我目前正在阅读的书中(C++没有恐惧)它说如果你没有为一个类声明一个默认的构造函数,编译器会为你提供一个,它将每个数据成员归零".我已经对此进行了试验,但没有看到任何归零行为.我也无法在 Google 上找到任何提及此内容的内容.这只是特定编译器的错误还是怪癖?

In the book I'm reading at the moment (C++ Without Fear) it says that if you don't declare a default constructor for a class, the compiler supplies one for you, which "zeroes out each data member". I've experimented with this, and I'm not seeing any zeroing -out behaviour. I also can't find anything that mentions this on Google. Is this just an error or a quirk of a specific compiler?

推荐答案

如果你没有定义构造函数,编译器会为你定义一个默认的构造函数.

If you do not define a constructor, the compiler will define a default constructor for you.

实现这个

  • 默认构造基类(如果基类没有默认构造函数,则编译失败)
  • 默认按照声明的顺序构造每个成员变量.(如果成员没有默认构造函数,这是编译失败).

注意:
POD 数据(int、float、pointer 等)没有显式构造函数,但默认操作是什么都不做(在 C++ 哲学的风向标中;除非我们明确要求,否则我们不想为某些东西付费).

Note:
The POD data (int,float,pointer, etc.) do not have an explicit constructor but the default action is to do nothing (in the vane of C++ philosophy; we do not want to pay for something unless we explicitly ask for it).

如果没有定义析构函数/复制构造函数/复制赋值运算符,编译器会为你构建其中一个(所以一个类总是有一个析构函数/复制构造函数/赋值运算符(除非你作弊并明确声明一个但没有定义)它)).
默认实现是:

If no destructor/copy Constructor/Copy Assignment operator is defined the compiler builds one of those for you (so a class always has a destructor/Copy Constructor/Assignment Operator (unless you cheat and explicitly declare one but don't define it)).
The default implementation is:

  • 如果定义了用户定义的析构函数,则执行提供的代码.
  • 以与声明相反的顺序调用每个成员的析构函数
  • 调用基类的析构函数.
  • 调用基类复制构造函数.
  • 按照声明的顺序为每个成员变量调用复制构造函数.
  • 调用基类赋值运算符
  • 按照声明的顺序调用每个成员变量的复制赋值运算符.
  • 返回对此的引用.

注意 POD 数据的复制构造/赋值运算符只是复制数据(因此存在与 RAW 指针相关的浅拷贝问题).

Note Copy Construction/Assignment operator of POD Data is just copying the data (Hence the shallow copy problem associated with RAW pointers).

如果没有定义析构函数/复制构造函数/复制赋值/移动构造函数/移动赋值运算符,编译器会为您构建移动运算符,其中之一是您.
默认实现是:

If no destructor/copy Constructor/Copy Assignment/Move Constructor/Move Assignment operator is defined the compiler builds the move operators for you one of those for you.
The default implementation is:

隐式声明的移动构造函数如果没有为类类型(结构、类或联合)提供用户定义的移动构造函数,并且以下所有条件都为真:

Implicitly-declared move constructor If no user-defined move constructors are provided for a class type (struct, class, or union), and all of the following is true:

  • 调用基类复制构造函数.
  • 按照声明的顺序为每个成员变量调用移动构造函数.
  • 调用基类赋值运算符
  • 按照声明的顺序调用每个成员变量的移动赋值运算符.
  • 返回对此的引用.

这篇关于C++ 中是否有隐式默认构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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