ringa_lee2017-04-17 12:06:31
It’s really hard to find such examples.
However, when the actual parameter content will definitely be modified, and this modification cannot affect the original variable, it is more suitable not to quote it.
For example:
bool read_file_in(string path, const string &file, string &out)
{
path += "/" + file;
return read_file(path, out);
}
bool write_file_in(string path, const string &file, const string &in)
{
path += "/" + file;
return write_file(path, in);
}
//...
string path, data;
//...
read_file_in(path, "in.txt", data);
write_file_in(path, "out.txt", data);
In the above example, is it better not to use a reference for the first parameter path?
迷茫2017-04-17 12:06:31
When using non-const references and the actual parameters are literal values, expressions, or objects of different types that need to be converted. Such as
void swap(int &a,int &b);
int a=2;
double b=3.0;
f(a,5);
f(a+2,a );
f(a,b);
will not work. You can't use const int& either, because the values of a and b need to be exchanged.