通过const引用或值传递int,有什么区别吗?
当我将 int
和 double
之类的原语传递给函数时,最好通过const引用或值传递它们(假设我不更改变量的值)?
When I pass primitives like int
and double
to functions , is it better to pass them by const reference , or by value (assuming that I don't change the variable's value) ?
int getValueFromArray(int index)
{
// return the value from the array
}
int getValueFromArray(const int& index)
{
// return the value from the array
}
谢谢
对于基本类型,按值传递比按引用传递要好得多.编译器不仅没有间接的引用,而且还具有参考意义,它不得不担心潜在的混叠现象,这可能会破坏优化机会.
For primitive types, passing by value is much better than passing by reference. Not only is there no indirection, but with a reference, the compiler has to worry about potential aliasing, which can ruin optimization opportunities.
最后,按引用传递会使左值变得奇特的使用,这实际上可能导致链接器错误.如果内联电话,这个最后的问题就不会消失.
Finally, pass-by-reference causes lvalues to become odr-used, which can actually cause linker errors. And this final issue doesn't go away if the call gets inlined.