C++构造与析构(13) - 内建类型的默认构造函数

参考下面的程序输出:

#include <iostream>
using namespace std;
int main() {
   cout << "output = " <<int() << endl;
   return 0;
}

输出结果:
output = 0

如果一个构造函数,没有任何参数,或者每个参数都带有默认值,则此函数是默认构造函数。编译器在需要时会调用此函数(还可能在必要时生成一些额外代码)。

C++甚至允许内建类型拥有默认构造函数。上面代码中,函数风格的int()相当于0. 因此程序打印结果为0。

下面是网络上一些关于内建类型的讨论,这里直接引用过来了:

It is worth to be cognizant of reference vs. value semantics in C++ and the concept of Plain Old Data types. From Wiki, primitive types and POD types have no user-defined copy assignment operator, no user-defined destructor, and no non-static data members that are not themselves PODs. Moreover, a POD class must be an aggregate, meaning it has no user-declared constructors, no private nor protected non-static data, no base classes and no virtual functions.

An excerpt (from a mail note) from the creator of C++, “I think you mix up ‘actual constructor calls’ with conceptually having a constructor. Built-in types are considered to have constructors”.

The code snippet above mentioned int() is considered to be conceptually having constructor. However, there will not be any code generated to make an explicit constructor call. But when we observe assembly output, code will be generated to initialize the identifier using value semantics. For more details refer section 8.5 of this document.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值