void swappedString (string& current) {
string newString = "bar";
current.swap(newString);
}
string func1() {
string result = "foo";
swappedString(result);
return result;
}
I wrote a code where I was swapping the contents of the string during a function call. The code is working fine. But I was skeptical whether this can result in UB.
I understand that the newString object will be created over the stack while resource for storing "bar" will be allocated in the free-store. Thus swapping the contents of the current string with the newString would be perfectly valid. And this also reduces the cost of returning the newString by value.
I'm adding one more example :
void nextString (string& current) {
string newString;
for (int iter = 0; iter < current.size(); ) {
int end = iter;
while (end + 1 != current.size() && current[iter] == current[end + 1]) ++end;
newString += std::to_string(end - iter + 1) + current[iter];
iter = end + 1;
}
current.swap(newString);
}
string LookAndSay(int n) {
if (n <= 0) return "";
string result = "1";
while (--n) {
nextString(result);
}
return result;
}