尽可能传递const引用参数

cho*_*ure 2 c++ parameters const pass-by-reference

可能重复:
C++:如何通过ref或value传递params?

以下函数是从C++ Primer,第5版和第214页编写的.此函数将返回字符串中第一次出现给定字符的位置,并告知该字符串中该字符的出现次数.

string::size_type find_char(const string &s, char c, string::size_type &occurs)
{
      // Compares the given character with string 
      // Records the first occurrence of that character
      // The change in &occurs is reflected back to the original variable
}
Run Code Online (Sandbox Code Playgroud)

作者建议在传递参数时使用"避免副本const参考",并对函数不变的参数使用" 参考参数".为什么他们不把char c一个const基准参数?

NPE*_*NPE 5

为什么他们不把char c一个const基准参数?

char如此小,通过价值而不是通过参考(const或其他方式)传递它通常更便宜.

  • @ChosenTorture可以说,*始终*按值传递原始类型是一个既定的约定.通过将`conts&`添加到基本类型参​​数(char,int,double ...),你得到**没有**,只有更少的readalbe代码.但你问为什么它为`string`做了,而不是为`char`做的?我认为这种差异是由*类型不同*引起的.`char`是原始的,`string`是*不*. (3认同)