C ++与Initializer List一件事,什么时候使用普通的构造函数? [英] C++ With Initializer List a thing, when to use normal constructor?

查看:48
本文介绍了C ++与Initializer List一件事,什么时候使用普通的构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近才刚开始回到C ++,并了解了初始化列表.这似乎是初始化成员的标准方法.话虽如此,我对此有2个问题:

I just started getting back into C++ here recently and learned about Initializer Lists. It seems to be the standard way to initialize members. That being said I have 2 questions regarding it:

  1. 是否有理由在设置私有成员变量时(仅在构造函数中使用老式的设置)不使用此方法.

  1. Is there ever a reason to NOT use this method when setting private member variables (and just using the old fashioned setting it in the constructor).

我们从中得到什么确切的好处?有人告诉我速度",但不完全是为什么?

What exact benefit do we get from this? I've been told "speed" but not exactly why?

edit:作为参考,我更具体地说是关于将它们用于类初始化.

edit: For reference Im more specifically speaking of using them for class initialization.

推荐答案

初始化列表与调用成员变量的ctor有关.如果分配,则通过使用assign函数来更改实例的值.显然,这两个是不同的功能.

Initialization list is about calling ctor of member variables. If you assign, you are altering the value of instance by using assign function. Obviously, these two are different functions.

在某些情况下,您无法将值分配给ctor中的成员变量.

There are a few cases that you cannot assign value to member variable in the ctor.

  • 当成员变量为const时.
  • 当成员变量是没有默认值的类的实例时ctor.
  • 当成员变量是引用时(与上述原因相同)
  • 初始化基类

当创建不带init-list的实例时,成员变量将运行其ctor,然后如果您为其赋值,则进行赋值.这是一个细微的差异,但由于ctor首先运行,而Assign运行第二,则可能会带来一些损失-

When you create an instance without init-list, the member variable runs its ctor and then assign if you give value to it. It's a subtle difference but it might incur some penalty as the ctor runs first, and assign runs 2nd - which is unnecessary overhead.

这篇关于C ++与Initializer List一件事,什么时候使用普通的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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