当我将像int
和double
这样的基本类型传递给函数时,是通过const引用传递还是通过值传递更好(假设我不改变变量的值)?
int getValueFromArray(int index)
{
// return the value from the array
}
int getValueFromArray(const int& index)
{
// return the value from the array
}
谢谢
当我将像int
和double
这样的基本类型传递给函数时,是通过const引用传递还是通过值传递更好(假设我不改变变量的值)?
int getValueFromArray(int index)
{
// return the value from the array
}
int getValueFromArray(const int& index)
{
// return the value from the array
}
谢谢
对于原始类型,传值比传引用更好。不仅没有间接性,而且使用引用时,编译器必须担心潜在的别名问题,这可能破坏优化机会。
最后,通过引用传递会导致左值变为odr-used,这实际上可能导致链接器错误。即使调用被内联,这个问题也不会消失。