When pre-allocating using std::string::reserve
do I have to add one for the terminating 0
explicitly in order to avoid re-allocation and subsequent copying?
For example, knowing that the string "Hello"
of length 5 will be stored in std::string str
, do I have to call str.reserve(6)
?
If I read the standard correctly, then I think the answer should be yes. For reserve
it says
After reserve(), capacity() is greater or equal to the argument of reserve.
and for capacity
in turn it states
Returns: The size of the allocated storage in the string.
I'm not to familiar with the subtleties of the formulations in the standard, though, and I wanted to confirm my suspicion.
Yes you can have embedded nulls in your std::string . Example: std::string s; s. push_back('\0'); s.
Surprised? You might be, because a std::string is often initialized from a null-terminated character string and often its value is used as a null-terminated character string, when c_str is called; but nonetheless a std::string is not a null-terminated character string. std::string s ( "\0\0test" , 6);
The String reserve() function allows you to allocate a buffer in memory for manipulating Strings.
The std::string class manages the underlying storage for you, storing your strings in a contiguous manner. You can get access to this underlying buffer using the c_str() member function, which will return a pointer to null-terminated char array. This allows std::string to interoperate with C-string APIs.
Returns: The size of the allocated storage in the string.
Allocated storage in the string that statement mean that string should fit in allocated space. "String" mean "zero-terminated group of char", so zero also should be included.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With