std::string_view (C++17) is a read-only, non-owning window onto characters: a pointer plus a length. Passing and slicing it never allocates.
Why use it
#include <iostream>
#include <string>
#include <string_view>
std::size_t countVowels(std::string_view text) { // accepts literals, std::string, substrings…
std::size_t n = 0;
for (char c : text) n += std::string_view("aeiou").find(c) != std::string_view::npos;
return n;
}
int main() {
std::string s = "education";
std::cout << countVowels(s) << ' ' << countVowels("sky") << '\n'; // no temporary std::string for "sky"
std::string_view sv = " trim me ";
sv.remove_prefix(sv.find_first_not_of(' '));
sv.remove_suffix(sv.size() - sv.find_last_not_of(' ') - 1);
std::cout << '[' << sv << "] " << sv.substr(0, 4) << '\n'; // substr is O(1): no copy
}5 0
[trim me] trimconst std::string& | std::string_view | |
|---|---|---|
Pass a literal "abc" | Creates a temporary std::string (may allocate) | No allocation |
substr | Copies → new string | O(1), shares the characters |
| Owns data | The referred string does | Never |
| Null-terminated | Yes (c_str()) | Not guaranteed |
| Can modify chars | No (const) | No |
The dangling trap
#include <iostream>
#include <string>
#include <string_view>
std::string makeGreeting() { return std::string(40, 'x'); }
int main() {
std::string_view sv = makeGreeting(); // view into a temporary that dies at the ';'
std::cout << sv << '\n'; // clang warns (-Wdangling-gsl); at run time: use-after-free
}When should a function take std::string by value instead of string_view?