利用const引用避免复制:
由于string对象可能相当长,所以我们希望避免复制操作。使用const引用就可避免复制

Code
//compare the length of two strings
bool isShorter(const string &s1,const string &s2)
{
return s1.size()<s2.size();
}
如果使用引用形参的唯一目的是避免复制实参,则应将形参定义为const引用。
使用非const引用有坏处:
应该将不修改相应实参的形参定义为const引用。如果将这样的形参定义为非const引用,则毫无必要地限制了该函数的使用。

Code
//returns index of first occurrence of c in s or s.size() if c isn't in s
//Note:s doesn't change,so it should be a reference to const
string::size_type find_char(string &s,char c)
{
string::size_type i=0;
while(i!=s.size()&&s[i]!=c)
++i; //not found, look at next character
return i;
}
这样的定义带来的问题是不能通过字符串字面值来调用这个函数

Code
if (find_char("Hello World", 'o')) //.....
虽然字符串字面值可以转换为string对象,但上述调用仍然会导致编译失败。
应该将不需要修改的引用形参定义为const引用。普通的非const引用形参在使用时不太灵活。这样的形参既不能用const对象初始化,也不能用字面值或产生右值的表达式实参初始化。