Let's say I have this code:
void MyFunc(const std::string& param) {
std::string maybe_altered_param;
if (ConditionIsMet()) {
maybe_altered_param = AlterParam(param);
} else {
maybe_altered_param = param; // <-- unnecessary copy
}
// do stuff with maybe_altered_param
// maybe_altered_param does not need to be modified further.
}
The AlterParam
function returns a copy of the string, so when ConditionIsMet
returns true, a copy is made in order to populate maybe_altered_param.
However, a copy is made also when ConditionIsMet()
returns false, which is suboptimal. In the second case I just want to have another name for the same object, without copies or anything of the sort.
What is the simplest way of removing the unnecessary copy in a case like this?