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

Nathan Myers ncm@cantrip.org
Thu Dec 11 17:08:00 GMT 2003


On Thu, Dec 11, 2003 at 03:51:36PM +0100, Neil Ferguson wrote:
> 
> Initial capacity:       0
> After 6 char assign:    6
> After reserve(1000000): 1003491
> After reserve():        1003491
> 
> 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.

When this was raised as a Defect Report, the committee recognized 
it as clunky, but not, technically, a Defect, and thus beyond their 
charter to change at that time.  For the next standard they have 
more latitude.

Nathan Myers
ncm-nospam@cantrip.org



More information about the Libstdc++ mailing list