默认构造函数

C++: Does the default constructor initialize built-in types

http://stackoverflow.com/questions/2417065/c-does-the-default-constructor-initialize-built-in-types

Implicitly defined (by the compiler) default constructor of a class does not initialize members of built-in types.

However, you have to keep in mind that in some cases the initialization of a instance of the class can be performed by other means. Not by default constructor, not by constructor at all.

For example, there's a widespread incorrect belief that for class C the syntax C() always invokes default constructor. In reality though, the syntax C() performs so called value-initialization of the class instance. It will only invoke the default constructor if it is user-declared. (That's in C++03. In in C++98 - only if the class is non-POD). If the class has no user-declared constructor, then the C() will not call the compiler-provided default constructor, but rather will perform a special kind of initialization that does not involve the constructor of C at all. Instead, it will directly value-initialize every member of the class. For built-in types it result in zero-initialization.

For example, if your class has no user-declared constructor

class C { 
  int i;
};

then the compiler will implicitly provide one, which will not initialize C::i

C c;
// `c.i` contains garbage

Nevertheless, the following initializations will zero-initialize i because they use the explicit () initializer

C c = C(); // does not use constructor for `C()` part
assert(c.x == 0);

C *pc = new C(); // does not use constructor
assert(pc->x == 0);

The behavior of () initializer is different in some respects between C++98 and C++03, but not in this case. For the above class C it will be the same: () initializer performs zero initialization of C::x.

Another example of initialization that is performed without involving constructor is, of course, aggregate initialization

C c = {}; // does not use constructor
assert(c.x == 0);
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值