See also std::vector capacity reduction and vector internal array: always on heap; cleaned up via RAII
string/vector use expandable arrays. Has to be allocated on heap not stack.
For vector, it’s very simple —
- resize() creates dummy elements iFF upsizing
- reserve() only allocates spare “raw” capacity without creating elements to fill it. See P279 [[c++stdLib]]
[[Optimized C++]] P70 confirms that std::string can get re-allocated when it grows beyond current capacity.
http://stackoverflow.com/questions/9521629/stdstringss-capacity-reserve-resize-functions compares std::string.resize() vs reserve().
- Backgrounder: Capacity — allocated capacity is often uninitialized memory reserved for this string.
- Backgrounder: size — length of the string that’s fully initialized and accessible. Some of the characters (nulls) could be invisible.
- string.resize() can increase the string’s size by filling in space (at the end) with dummy characters (or a user-supplied char). See http://www.cplusplus.com/reference/string/string/resize/
- After resize(55) the string size is 55. All 55 characters are part of the string proper.
- changes string’s size
- string.reserve() doesn’t affect string size. This is a request to increase or shrink the “capacity” of the object. I believe capacity (say 77) is always bigger than the size of 55. The 77 – 55 = 22 extra slots allocated are uninitialized! They only get populated after you push_back or insert to the string.