title: is a += a safe for std::string in c++
body: <p>Is the following code safe in C++</p>
  <pre><code>std::string a = &quot;foo&quot;;
  a += a;
  </code></pre>
  <p>I suspect the answer is no, but I'm struggling to find any documentation either way on this.</p>
  <blockquote>
  <p>What's your particular doubt?</p>
  </blockquote>
  <p>The relevant overloaded operator is declared as.</p>
  <pre><code>string&amp; operator+= (const string&amp; str);
  </code></pre>
  <p>My doubt is whether <code>operator+=</code> is required to guard against situations where <code>this</code> and <code>str</code> refer to the same object.</p>
  <p>It seems to me that += must perform the following operations.</p>
  <ul>
  <li>Calculate the length of the new string from the size of the two existing strings.</li>
  <li>Re-size the destination buffer (possibly relocating it)</li>
  <li>Copy the characters from the source buffer to the destination buffer.</li>
  <li>Store the new length.</li>
  </ul>
  <p>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.</p>
  <ul>
  <li>A stale pointer could be used for the source of the copy, resulting in a &quot;use after free&quot;.</li>
  <li>The new length rather than the old length could be used for the number of characters to copy resulting in a &quot;buffer overflow&quot;.</li>
  </ul>
  <p>So the question is are implementers required to implement <code>operator+=</code> in a manner that is safe when <code>this and str</code> refer to the same object.</p>