通过const引用或值传递int,有什么区别吗? [英] Pass int by const reference or by value , any difference?

查看:87
本文介绍了通过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.

这篇关于通过const引用或值传递int,有什么区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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