blob: 8b3596a3074ab15a72d7900cc77e61f3950fa1d4 [file] [log] [blame]
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>Shrink to Fit</title><meta name="generator" content="DocBook XSL Stylesheets V1.74.0" /><meta name="keywords" content="&#10; ISO C++&#10; , &#10; library&#10; " /><link rel="home" href="../spine.html" title="The GNU C++ Library Documentation" /><link rel="up" href="bk01pt05ch13.html" title="Chapter 13. String Classes" /><link rel="prev" href="bk01pt05ch13s04.html" title="Tokenizing" /><link rel="next" href="bk01pt05ch13s06.html" title="CString (MFC)" /></head><body><div class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="3" align="center">Shrink to Fit</th></tr><tr><td width="20%" align="left"><a accesskey="p" href="bk01pt05ch13s04.html">Prev</a> </td><th width="60%" align="center">Chapter 13. String Classes</th><td width="20%" align="right"> <a accesskey="n" href="bk01pt05ch13s06.html">Next</a></td></tr></table><hr /></div><div class="sect1" lang="en" xml:lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="strings.string.shrink"></a>Shrink to Fit</h2></div></div></div><p>
</p><p>From GCC 3.4 calling <code class="code">s.reserve(res)</code> on a
<code class="code">string s</code> with <code class="code">res &lt; s.capacity()</code> will
reduce the string's capacity to <code class="code">std::max(s.size(), res)</code>.
</p><p>This behaviour is suggested, but not required by the standard. Prior
to GCC 3.4 the following alternative can be used instead
</p><pre class="programlisting">
std::string(str.data(), str.size()).swap(str);
</pre><p>This is similar to the idiom for reducing a <code class="code">vector</code>'s
memory usage (see <a class="ulink" href="../faq/index.html#5_9" target="_top">FAQ 5.9</a>) but
the regular copy constructor cannot be used because libstdc++'s
<code class="code">string</code> is Copy-On-Write.
</p></div><div class="navfooter"><hr /><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="bk01pt05ch13s04.html">Prev</a> </td><td width="20%" align="center"><a accesskey="u" href="bk01pt05ch13.html">Up</a></td><td width="40%" align="right"> <a accesskey="n" href="bk01pt05ch13s06.html">Next</a></td></tr><tr><td width="40%" align="left" valign="top">Tokenizing </td><td width="20%" align="center"><a accesskey="h" href="../spine.html">Home</a></td><td width="40%" align="right" valign="top"> CString (MFC)</td></tr></table></div></body></html>