本文介绍了i ++,或++ i,哪个更快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

c ++标准库,教程和参考它说:


++我比i ++快。后者涉及一个临时对象因为

它必须返回i的旧值/对象。出于这个原因,使用++ i通常会更好。


但是,我认为,即使是++我仍然必须返回带有新值的临时对象是

。所以,i ++和++我必须返回一个临时的

对象。然后,i ++和++ i之间的速度差异是什么。

解决方案




前缀版本通过引用返回,因此不需要临时副本。


-Howard





我还在学习C / C ++,但我刚刚完成的那一章处理过

重载运算符,包括后缀和前缀增量/减量。

根据我的理解和我做的赋值,前缀

递增/递减,++ i在你的例子中,增加了对象的值,

然后返回它。后缀增量/减量,在你的例子中是i ++,

复制对象的当前值,增加

对象的当前值,并返回副本的值。因此,前缀只有两个步骤,

其中后缀有三个。


我的解释是否正确?


戴夫





不,我认为++我会返回对i的引用。 ++我返回一个新对象

包含旧的i值。对于原始类型,速度

的差异可以忽略不计。但是,如果你写了一个为每个实例分配10

兆字节内存的类,差别就会很大。


Kristo


"the c++ standard library, tutorial and reference" book, it says:

++i is faster than i++. the latter involves a temporary object because
it must return the old value/object of i. for this reason, it''s
generally better to use ++i.

but, I think, even ++i still has to return a temporary object that is
with new value inside. So, both i++ and ++i have to return a temporary
object. Then, what''s the speed difference between i++ and ++i.

解决方案



The prefix version returns by reference, so no temporary copy is needed.

-Howard




I''m still learning C/C++, but the chapter I just finished dealt with
overloading operators, including postfix and prefix increment/decrement.
According to my understanding and the assignment I did, the prefix
increment/decrement, ++i in your example, increases the value of the object,
and then returns it. The postfix increment/decrement, i++ in your example,
copies the current value of the object, increases the current value of the
object, and returns the value of the copy. Thus, prefix only has two steps,
where postfix has three.

Is my interpretation correct?

Dave




No, I think ++i returns a reference to i. ++i returns a new object
containing the old value of i. For primitive types, the speed
difference negligible. But, if you wrote a class that allocated 10
megabytes of memory for each instance, the difference would be huge.

Kristo


这篇关于i ++,或++ i,哪个更快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 21:56