Why string_view
Avoid string copies.
The Cost of Copies
Passing std::string by value copies the whole buffer. For read-only access that copy is wasted work. std::string_view is a lightweight, non-owning view, just a pointer and a length. Include <string_view>.
#include <iostream>
#include <string_view>
int main() {
std::string_view sv = "hello";
std::cout << sv << " len=" << sv.size() << "\n";
}What a View Holds
A string_view stores only a pointer to existing characters and a length. It does not own or copy the data.
#include <iostream>
#include <string>
#include <string_view>
int main() {
std::string s = "world";
std::string_view sv = s; // views s, no copy
std::cout << sv << "\n";
}All lessons in this course
- Why string_view
- Creating Views
- Pitfalls and Lifetimes
- String Algorithms