In general std::string_view::data()
does not guarantee zero termination of the data refered to by the std::string_view
.
From the documentation Notes section:
Unlike std::basic_string::data() and string literals,
std::basic_string_view::data() returns a pointer to a buffer that is
not necessarily null-terminated, for example a substring view (e.g.
from remove_suffix). Therefore, it is typically a mistake to pass
data() to a routine that takes just a const CharT* and expects a
null-terminated string.
(emphasis is mine)
The following short program demostrates it:
#include <string_view>
#include <iostream>
int main() {
char str[] = "abcdefghij";
std::string_view sv{ str, 2 };
std::cout << sv << std::endl;
std::cout << sv.data() << std::endl;
}
Possible output:
ab
abcdefghij
Live demo
Note that sv
is only 2 characters (and std::cout
prints it well), but when you access data()
and attemtping to print it there is no zero termination where it is supposed to be. In this specific case (which is by no means a general rule) the zero termination comes eventually along the buffer from the char array str
.
However - If your std::string_view
is initialized to a whole (complete) zero terminated string (like a char array or std::string
), then the data() pointer will probably "inherit" the zero termination from it. I am not sure if it is implementation depenedent.