Using string.erase() making a string longer?
<p>I ran into this issue on accident while debugging a faulty string trim function and now I'm wondering what exactly is causing this behavior.</p>

<p>Here's a code snippet with just the relevant bits:</p>

<pre><code>#include &lt;iostream&gt;
#include &lt;string&gt;
using namespace std;

void debug(string s) { cout &lt;&lt; "Len: " &lt;&lt; s.length() &lt;&lt; "; Value: '" &lt;&lt; s &lt;&lt; "'" &lt;&lt; endl; }

int main()
{
    string str = "ABC";
    debug(str);

    str.erase( str.begin() + 4, str.end() );  // Magic!
    debug(str):

    return 0;
}
</code></pre>

<p>You'll notice that the erase function is taking an iterator that starts just beyond the end of the string.  This isn't the exact input used when I ran into the issue (it was having a +1 which broke empty strings), but it has a similar effect.  Here's the output:</p>

<pre><code>Len: 3; Value: 'ABC'
Len: 4; Value: 'ABC '
</code></pre>

<p>When I change the <code>str.begin() + 4</code> to something greater like <code>+ 10</code> it becomes clear that I'm starting to pull in garbage data.  </p>

<p>My question is: how is it that using the erase() function ends up making the string <em>longer</em> than before?  Also, is it just luck, or is the next character after the end of the string always whitespace?</p>
