C ++创建对象,初始化列表与赋值? [英] C++ Creating objects, initialization lists vs assignment?

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

问题描述

我最近和一个朋友讨论过,他们说当你在C ++中创建对象时使用初始化列表(而不是简单地分配数据成员)有一个性能提升。

I was recently discussing with a friend and they said there is a performance gain when you use an initialization list to (as opposed to not and simply assigning the data members) when creating objects in C++.

为什么是这个(如果是真的)?

Why is this (if it is true)?

我发现这个网页:

http://www.parashift.com/c++-faq/init- lists.html

他们提到临时对象,但我想最近的编译器可以避免这种情况?

and they mention temporary objects but I would have thought recent compilers could avoid this?

推荐答案

使用赋值时,对象在你到达赋值之前是默认构造的。如果构造和复制对象是昂贵的操作,你应该至少摆脱其中之一。初始化列表除去了附加复制操作。复制构造允许同时进行。

When using assignment, the objects are default constructed before you get to the assignment. If constructing and copying an object are expensive operations, you should at least get rid of one of them. An initialization list gets rid of the additional copying operation. Copy constructing allows to do both at the same time.

这篇关于C ++创建对象,初始化列表与赋值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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