There is no guaranteed minimum capacity for std::string
. You can request whatever capacity you want by calling reserve
but an particular implementation only guarantees to set capacity to some amount greater than or equal to the requested size.
Here's a modified version of your program which tests several methods of string shrinking:
#include <string>
#include <iostream>
using namespace ::std;
template< typename S >
S & reserve_request( S & s, typename S::size_type n ) {
s.reserve( n ); return s;
}
template< typename S >
S & shrink_request1( S & s ) { s.reserve(); return s; }
template< typename S >
S & shrink_request2( S & s ) { S( s ).swap( s ); return s; }
template< typename S >
S & shrink_request3( S & s ) { S( s.c_str() ).swap( s ); return s; }
template< typename S >
void test( S & s ) { cout << s.capacity() << endl; }
int main() {
string temp = "1234567890123456"; // length 16
string str;
test( str ); // 15
test( reserve_request( str, 16 ) ); // 31
test( str += temp ); // 31
test( reserve_request( str, 16 ) ); // 31
test( shrink_request1( str ) ); // 31
test( shrink_request2( str ) ); // 31
test( shrink_request3( str ) ); // 31
return 0;
}
It would appear that Visual C++'s std::string
typically keeps some spare capacity.
If your project loads large numbers of strings read in from an external source whose size then never changes, you might be better off (as others have suggested) storing them in a single big block of character memory separated by '\0'
characters (i.e., as C-strings). If you like, you could provide wrapper functions that return std::string
s on the fly.