使用初始化列表的优点? [英] Advantages of using initializer list?

查看:363
本文介绍了使用初始化列表的优点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

初始化列表的好处

我想知道是否有优势使用初始化器列表来初始化成员将它们放在构造函数中。某些东西必须使用初始化列表,但对于大多数不是的东西,有什么区别吗?我喜欢后者,因为当我有多个构造函数,我更喜欢简单地调用construct()来促进代码重用。

I was wondering if there was an advantage to initializing members with the initializer list over putting these in the constructor. Certain things have to use the initialize list but for the majority of things that don't, is there a difference? I prefer the latter because when I have multiple constructors, I prefer simply calling construct() to promote code reuse.

谢谢

推荐答案

如果不使用初始化器列表,成员或基类将在开头大括号前创建默认值。

If you don't use the initializer list, the member or base class gets default constructed before the opening curly brace.

因此,稍后设置它的调用将添加 operator =()调用。

So, your calls to set it later will add an operator=() call.

如果使用初始化器列表,则成员或基类具有正确的构造函数。

If you use the initializer list, the member or base class has the proper constructor called.

你的类,这可能是必需的或更快。

Depending on your classes, this might be required or faster.

这篇关于使用初始化列表的优点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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