简体   繁体   中英

std::basic_string::reserve() specifics

I was reading the standard on std::basic_string::reserve(size_type res_arg=0) . It says this:

void reserve(size_type res_arg=0);

The member function reserve() is a directive that informs a basic_string object of a planned change in size, so that it can manage the storage allocation accordingly.

Effects: After reserve() , capacity() is greater or equal to the argument of reserve. [ Note: Calling reserve() with a res_arg argument less than capacity() is in effect a non-binding shrink request. A call with res_arg <= size() is in effect a non-binding shrink-to-fit request. — end note ]

Throws: length_error if res_arg > max_size()

The standard seems to be making a distinction between calling reserve() where res_arg < capacity() and calling reserve() where res_arg <= size() .

res_arg <= size() is easy to understand, shrink_to_fit() is called and the implementation is free to do whatever it wants since it's non-binding.

But what about cases where res_arg < capacity() ? The standard says " a non-binding shrink request " and not " a non-binding shrink-to-fit request ". What is the difference between a shrink-to-fit request and a shrink request? Is this just an unfortunate inconsistency?

std::string::shrink_to_fit() will shrink the capacity() to the size() . That is differnt then shrinking the capacity() to a number less than capacity() but more than size() . In effect

std:string foo = "test";
foo.reserve(20);      // capaicty:20 size:4
foo.reserve(10);      // capaicty:10 size:4
foo.reserve(20);      // capaicty:20 size:4
foo.shrink_to_fit();  // capaicty:04 size:4

shrink to fit: Reduce capacity to fit size.

First mention on google is for a vector .

Shrink just well, shrinks (capacity down). If you're reserving less then the current size in essence that would be preparing to reduce the container to fit a shorter string, hence the 'fit'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM