C++临时对象

考虑以下代码:

1
2
3
4
5
6
7
8
string foo(){ return string("temp");}
void bar(string &s){}
int main()
{
/*bar(foo());*/
bar("temp");
cout<<"success"<<endl;
}

上面的代码会引发错误

1
conference.cpp:15:2: error: no matching function for call to 'bar' bar("temp");

原因在于foo()和“temp”都会产生一个临时对象,而在c++中,这些临时对象都是const类型的。因此上面的程序就是试图将一个const类型的对象转换为非const类型,这是非法的。
因此,在确定函数内部不会改变参数时,尽量将引用定义为常引用。