Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>As Vlad and Alf commented, <code>std::string().swap(the_string)</code> is the C++98 way to release <code>the_string</code>'s capacity, and <code>the_string.shrink_to_fit()</code> is the C++11 way.</p> <p>As to why <code>clear()</code>, <code>erase()</code>, <code>resize()</code>, etc. don't do it, this is an optimization to reduce allocations when you use a string over and over. If <code>clear()</code> freed the string's capacity, you'd generally have to reallocate a similar amount of space on the next iteration, which would take some time the implementation can save by keeping the capacity around. This implementation isn't guaranteed by the standard, but it's very common in implementations.</p> <p><code>reserve()</code> is documented with</p> <blockquote> <p>Calling reserve() with a res_arg argument less than capacity() is in effect a non-binding shrink request. A call with res_arg &lt;= size() is in effect a non-binding shrink-to-fit request.</p> </blockquote> <p>which implies that implementations are more likely to release the capacity on a <code>reserve()</code> call. If I'm reading them right, <a href="http://llvm.org/viewvc/llvm-project/libcxx/trunk/include/string?view=markup" rel="nofollow">libc++</a> and libstdc++ do release space when you call <code>reserve(0)</code>, but it's plausible for VC++'s library to have made the opposite choice.</p> <p>Edit: As penelope says, <code>std::string</code>'s behavior here tends to be exactly the same as <code>std::vector</code>'s behavior.</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