在这种特殊情况下,使用成员初始化器列表和在构造函数中分配值之间是否有区别? [英] In this specific case, is there a difference between using a member initializer list and assigning values in a constructor?

查看:212
本文介绍了在这种特殊情况下,使用成员初始化器列表和在构造函数中分配值之间是否有区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在内部和生成的代码,是有一个真正的区别:

Internally and about the generated code, is there a really difference between :

MyClass::MyClass(): _capacity(15), _data(NULL), _len(0)
{
}

MyClass::MyClass()
{
  _capacity=15;
  _data=NULL;
  _len=0
}

谢谢...

推荐答案

假设这些值是原始类型,那么没有,没有区别。初始化列表仅在作为成员的对象时有所不同,因为初始化列表可以将对象初始化为其最终值,而不是使用默认初始化随后分配。这实际上可以明显更快。

Assuming that those values are primitive types, then no, there's no difference. Initialization lists only make a difference when you have objects as members, since instead of using default initialization followed by assignment, the initialization list lets you initialize the object to its final value. This can actually be noticeably faster.

这篇关于在这种特殊情况下,使用成员初始化器列表和在构造函数中分配值之间是否有区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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