Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can easily see the behavior of your implementation by calling <code>std::string::capacity</code> at various times. In general, I'd be surprised if any implementation ever had a buffer of three characters. (Not words, but bytes, at least on most modern machines.) In practice, implementations vary, and also vary depending on how the new length comes about: with g++, for example, removing characters with <code>std::string::erase</code> will not reduce the capacity of the string, but assigning a new, smaller string will. VC++ doesn't reduce the capacity in either case. (In general, VC++ and g++ have very different strategies with regards to memory management in strings.)</p> <p>EDIT:</p> <p>Given the other responses (which don't even correspond to usual practice): here's the small test program I used to verify my statements above (although I really didn't need it for g++&mdash;I know the internals of the implementation quite well):</p> <pre><code>#include &lt;string&gt; #include &lt;iostream&gt; #include &lt;iomanip&gt; template&lt;typename Traits&gt; void test() { std::string s; size_t lastSeen = -1; std::cout &lt;&lt; Traits::name() &lt;&lt; ": Ascending:" &lt;&lt; std::endl; while ( s.size() &lt; 150 ) { if ( s.capacity() != lastSeen ) { std::cout &lt;&lt; " " &lt;&lt; std::setw( 3 ) &lt;&lt; s.size() &lt;&lt; ": " &lt;&lt; std::setw( 3 ) &lt;&lt; s.capacity() &lt;&lt; std::endl; lastSeen = s.capacity(); } Traits::grow( s ); } std::cout &lt;&lt; Traits::name() &lt;&lt; ": Descending: " &lt;&lt; std::endl; while ( s.size() != 0 ) { Traits::shrink( s ); if ( s.capacity() != lastSeen ) { std::cout &lt;&lt; " " &lt;&lt; std::setw( 3 ) &lt;&lt; s.size() &lt;&lt; ": " &lt;&lt; std::setw( 3 ) &lt;&lt; s.capacity() &lt;&lt; std::endl; lastSeen = s.capacity(); } } std::cout &lt;&lt; "Final: capacity = " &lt;&lt; s.capacity() &lt;&lt; std::endl; } struct Append { static void grow( std::string&amp; s ) { s += 'x'; } static void shrink( std::string&amp; s ) { s.erase( s.end() - 1 ); } static std::string name() { return "Append"; } }; struct Assign { static void grow( std::string&amp; s ) { s = std::string( s.size() + 1, 'x' ); } static void shrink( std::string&amp; s ) { s = std::string( s.size() - 1, 'x' ); } static std::string name() { return "Assign"; } }; int main() { test&lt;Append&gt;(); test&lt;Assign&gt;(); return 0; } </code></pre> <p>Try it. The results are quite instructive.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload