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.

4
  • What's your particular doubt? I don't see anything ill formed from this code?!? Commented Apr 16, 2021 at 21:33
  • I assume you're wondering because 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. Commented Apr 16, 2021 at 21:36
  • 1
    It is safe. As safe as if you had done a = a + a; Commented Apr 16, 2021 at 21:37
  • You question asks about operator +=, but per this, operator += has the same behavior as append so I'm closing to the append Q. Commented Apr 16, 2021 at 21:47

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.