0

Is the following code safe in C++

std::string a = "foo";
a += a;

I suspect the answer is no, but I'm struggling to find any documentation either way on this.

What's your particular doubt?

The relevant overloaded operator is declared as.

string& operator+= (const string& str);

My doubt is whether operator+= is required to guard against situations where this and str refer to the same object.

It seems to me that += must perform the following operations.

  • Calculate the length of the new string from the size of the two existing strings.
  • Re-size the destination buffer (possibly relocating it)
  • Copy the characters from the source buffer to the destination buffer.
  • Store the new length.

Depending on the precise order in which these operations are performed and whether or not values are cached in local variables, I can see at least two ways this could go wrong.

  • A stale pointer could be used for the source of the copy, resulting in a "use after free".
  • The new length rather than the old length could be used for the number of characters to copy resulting in a "buffer overflow".

So the question is are implementers required to implement operator+= in a manner that is safe when this and str refer to the same object.

plugwash
  • 9,724
  • 2
  • 38
  • 51
  • What's your particular doubt? I don't see anything ill formed from this code?!? – πάντα ῥεῖ Apr 16 '21 at 21:33
  • I assume you're wondering because [`operator+=`](https://en.cppreference.com/w/cpp/string/basic_string/operator+=) takes a reference to the right-hand side. And for this case the left-hand side and the right-hand- side is the same object. – Some programmer dude Apr 16 '21 at 21:36
  • 1
    It is safe. As safe as if you had done `a = a + a;` – Eljay Apr 16 '21 at 21:37
  • You question asks about `operator +=`, but per [this](https://timsong-cpp.github.io/cppwp/string.op.append), `operator +=` has the same behavior as `append` so I'm closing to the append Q. – NathanOliver Apr 16 '21 at 21:47

0 Answers0