-1
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;
}
Ajay Singh
  • 464
  • 6
  • 10
  • I might be wrong, but it's not necessary that any space is allocated to hold `"bar"`, thanks to [SSO](https://blogs.msmvps.com/gdicanio/2016/11/17/the-small-string-optimization/). – Enlico Jun 13 '21 at 20:37
  • The compiler probably already optimizes this for you. Related: [https://stackoverflow.com/questions/12953127/what-are-copy-elision-and-return-value-optimization](https://stackoverflow.com/questions/12953127/what-are-copy-elision-and-return-value-optimization) – drescherjm Jun 13 '21 at 20:38
  • I gave this as an example. It can be a bigger string. – Ajay Singh Jun 13 '21 at 20:42
  • 2
    This seems worse than `current = "bar";` – M.M Jun 13 '21 at 20:59

1 Answers1

1

But I was skeptical whether this can result in UB.

There is no undefined behaviour in the example program.

To elaborate: There is no rule in the language that would say the behaviour of this program to be undefined.

And this also reduces the cost of returning the newString by value.

It doesn't.

eerorika
  • 232,697
  • 12
  • 197
  • 326