本文介绍了传递整数作为经常提到与复制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个愚蠢的问题,但我注意到,在一个良好的许多API,很多是采取不打算修改样子整数参数的方法签名:

This might be a stupid question, but I notice that in a good number of APIs, a lot of method signatures that take integer parameters that aren't intended to be modified look like:

无效的方法(INT X);

而不是:

无效的方法(const int的&安培; X);

对我来说,它看起来像这两个会的功能的完全一样。 (编辑:显然没有在某些情况下,看到由R塞缪尔Klatchko回答)在前者中,该值被复制,因此不能改变原。在后者中,恒定的参考被传递,所以原来不能被改变。

To me, it looks like both of these would function exactly the same. ( apparently not in some cases, see answer by R Samuel Klatchko) In the former, the value is copied and thus can't change the original. In the latter, a constant reference is passed, so the original can't be changed.

我想知道的是,为什么一个比其他 - 它是因为性能基本相同甚至更好的与前?例如通过一个16位值或32位值,而不是32位或64位的地址?这是唯一合乎逻辑的原因,我能想到的,我只是想知道这是否是正确的,如果没有,为什么当你将preFER INT X 结束 const int的&放大器; X 和/或反之亦然。谢谢你。

What I want to know is why one over the other - is it because the performance is basically the same or even better with the former? e.g. passing a 16-bit value or 32-bit value rather than a 32-bit or 64-bit address? This was the only logical reason I could think of, I just want to know if this is correct, and if not, why and when you would prefer int x over const int &x and/or vice versa. Thanks.

推荐答案

这不是传递指针的只是费用(这基本上是一个参考是什么),但在被调用方法的身体也去参照检索底层值。

It's not just the cost of passing a pointer (that's essentially what a reference is), but also the de-referencing in the called method's body to retrieve the underlying value.

这就是为什么传递一个 INT 按值将几乎可以肯定要快(此外,编译器可以优化并简单地通过 INT 通过处理器寄存器,而无需将它推入堆栈)。

That's why passing an int by value will be virtually guaranteed to be faster (Also, the compiler can optimize and simply pass the int via processor registers, eliminating the need to push it onto the stack).

这篇关于传递整数作为经常提到与复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 20:15