Consider this function:
bool doSomething( const std::string& str );
It takes a std::string
by reference as it does not modify it. OK.
Now, let's suppose that the function needs to modify the parameter as pre-processing in order to get its decision and return:
bool doSomething( const std::string& str )
{
std::string copy = str;
// preprocessing: modify copy
return copy.size(); // or anything else, where test on copy
// is different than test on str
// due to preprocessing operation
}
Often, when I have this, I prefer to change the function prototype to bool doSomething( std::string str )
. I like it because it prevents bugs where developer (me) could accidentally use str
instead of copy
in the function implementation...(it happened in the past).
But people reading my header file will often say, "Hey, why are you passing this object by copy, not by const reference, that's bad...?".
Question: is passing by copy in this specific case (where the function will for sure do a copy internally) a good or bad practice?