I have some code that is part of a larger function that is working. However, in order to optimize it and eliminate the unnecessary need for string copying I want to rewrite this code with references. My code relies on largerStr being a longer string than smallerStr. I want to rewrite this with references but I can't seem to get it to work. If I try and make largerStr and smallerStr references without explicitly initializing them the compiler tells me need to initialize it at declaration. If I try and put it as a temporary variable in the if statement I end up having both variables referencing the same string.
What is the best solution?
//str1 and str2 are std::strings
std::string largerStr, smallerStr;
if(str1.length() > str2.length()) {
largerStr = str1;
smallerStr = str2;
} else {
largerStr = str2;
smallerStr = str1;
}