There is no minimum capacity for std::string . You can request any required capacity by calling reserve , but a specific implementation only guarantees that the capacity is set to a certain amount greater or equal to the required size.
Here's a modified version of your program that tests several string compression methods:
#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 seems that Visual C ++ std::string usually saves some reserve capacity.
If your project loads a large number of lines read from an external source, the size of which never changes, you might be better off (as others suggested) to store them in one large block of character memory, separated by the characters '\0' (i.e. as C -line). If you like, you can provide wrapper functions that return std::string on the fly.
jwfearn
source share