在这种特定情况下,使用成员初始值设定项列表和在构造函数中赋值之间有区别吗?

2021-12-01 00:00:00 initialization c++ initialization-list

内部和关于生成的代码,是否真的有区别:

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.

相关文章