If you look at the source of basic_string
in libstdc you can see that this is done in the _M_create
function:
// NB: Need an array of char_type[__capacity], plus a terminating
// null char_type() element.
return _S_allocate(_M_get_allocator(), __capacity + 1);
So for the libstdc
, yes this is done.
But if this is required or not depends entirely on how the memory is handled by the underlying implementation. If e.g. the underlying OS would already guarantee that for a given pointer, an access after the allocated memory would always result in a \0
, then this would not be required.
A side note:
An implementation could (and this is AFAIK also done for the small string optimization part) use the memory which contains the information about the length of the string also for the null termination part.
So you could have something like this:
struct string {
size_t capacity;
char* data;
}
And data could look like this:
[number of bytes equal to capacity][bytes required for storing length]
Length is stored as max_capacity-lenght_of_string
so if the string reaches maximum capacity the bytes storing the length will be 0
and could then serve as the null termination so no additional byte for the \0
would need to be allocated (only the ones for the length).