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.
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.a = a + a;operator +=, but per this,operator +=has the same behavior asappendso I'm closing to the append Q.