[v3] basic_string::reserve() shrink-to-fit?

Nathan Myers ncm-nospam@cantrip.org
Thu Dec 11 17:36:00 GMT 2003


On Thu, Dec 11, 2003 at 05:20:20PM +0000, Jonathan Wakely wrote:
> On Thu, Dec 11, 2003 at 09:08:33AM -0800, Nathan Myers wrote:
> 
> > > ie. reserve() doesn't seem to shrink the string capacity to fit.
> > 
> > I'm afraid that's what's supposed to happen, in basic_string<> and 
> > in vector<>.  The idiom for shrinking to fit is to use swap().
> > Minimally,
> > 
> >   std::swap(std::string(str.data(), str.size()), str);
> > 
> > This might be a good thing to put in the FAQ.
> 
> I'll prepare a FAQ entry tonight if noone beats me too it.
> 
> For the purposes of the FAQ, is the above form preferred to either
> 
>   std::string(str.data(), str.size()).swap(str);
> 
> which the first form will defer to, or
> 
>   std::swap(std::string(str.begin(), str.end()), str);
> 
> which doesn't use std::string::data() and so works for vectors too?

For string, they're about equivalent.  Probably your first is best.
For vector, the shorter

  std::vector<T>(v).swap(v);

is preferred.  I.e. vector isn't copy-on-write, so a regular copy 
suffices to construct the temporary.

Thank you for the quick uptake.

Nathan Myers
ncm-nospam@cantrip.org



More information about the Libstdc++ mailing list