Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::string::reserve and end-of-string 0

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.

like image 752
Xlea Avatar asked May 07 '15 20:05

Xlea


People also ask

Can std::string contain 0?

Yes you can have embedded nulls in your std::string . Example: std::string s; s. push_back('\0'); s.

Is std::string zero terminated?

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);

What is string Reserve?

The String reserve() function allows you to allocate a buffer in memory for manipulating Strings.

What does std::string () do?

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.


1 Answers

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.

like image 62
Tomasz Pluta Avatar answered Oct 11 '22 17:10

Tomasz Pluta