Loading lessons...
std::string_view
std::string_view
Copying text can be expensive. std::string_view is a read-only view: it points at existing text without copying it.
A view, not a copy
#include <string_view>
std::string_view sv = "hi";
sv does not own the characters. It is like a tag attached to someone else's string - a pointer and a length, nothing more.
Passing strings cheaply
void printLength(std::string_view text) {
cout << text.size() << endl;
}
printLength("hello"); // no copy needed
Functions that only read a string can take a string_view and skip the copy. It also accepts C-style strings and string literals directly.
The lifetime caveat
The view only lives as long as the text it points to:
std::string_view sv;
{
std::string temp = "hello";
sv = temp; // sv points into temp
} // temp dies here
cout << sv << endl; // danger: dangling view!
If the original string is destroyed while the view still points at it, reading the view is undefined behavior. As long as the source outlives the view, you are fine.
Efficiency
- No copy: great for reading big strings many times.
- No allocation: it does not grow or manage memory.
- Read-only: you cannot modify the text through it.
Use string_view when you just need to look, and string when you need your own copy.
TL;DR
std::string_viewis a read-only view of text, no copy.- Accepts std::string, C-style strings, and literals.
- The viewed string must outlive the view.
- Prefer it for read-only parameters; use
stringwhen you need ownership.