std::string_view
(C++)
my manager at Tesla loved using this.
string_view
is a wrapper around std::string
that allows us to work with various types of strings.
Remember that std::string
is just a wrapper around the C-Style string.
Resources
- https://en.cppreference.com/w/cpp/string/basic_string_view
- https://jaredmil.medium.com/c-std-string-view-explained-89df5ba6b25e
I don't get the point of string_view, when you can literally just pass a
const string&
?Like an array of char can also be implicitly cast?
Not really.
std::string s = "Hello, world!";
char char_s[] = {'h', 'e', 'l', 'l', 'o', '\0'};
print_substring(s); // From std::string
print_substring(char_s); // c string
print_substring("Temporary literal"); // From string literal
print_substring(std::string_view(s).substr(0, 5)); // "Hello"
// THIS WORKS
void print_substring(std::string_view str) {
std::cout << str << "\n";
}
// THIS DOES NOT WORK for c_style strings
void print_substring(std::string& str) {
std::cout << str << "\n";
}