Non-Owning Views with string_view in C++
std::string_view (C++17, <string_view>) is a read-only window onto someone else's characters — a pointer plus a length, copied for the price of two words, never allocating. Passing string_view instead of const std::string& accepts strings, literals, and substrings uniformly with zero copies and zero temporaries.
The contract is non-ownership: the viewed text must outlive every view of it, and views are not null-terminated (never pass .data() to C functions expecting termination). For parsing, splitting, and read-only parameters, string_view is the modern default.
View, don't own
std::string_view v = "hello"; points at the literal's storage — no allocation, no copy, just a pointer and a size.
Accept everything readable
void f(std::string_view s) takes std::string, literals, and other views alike — one signature replaces overload sets.
Substring without copying
v.substr(0, 5) and v.remove_prefix(3) carve views in O(1) — tokenizers that never allocate.
Lifetime is on you
Returning a view of a local string dangles — views borrow, and borrowers must not outlive lenders. Never feed .data() to C APIs needing termination.
#include <iostream>#include <string>#include <string_view> int main() { std::string text = "hello world"; std::string_view first(text.data(), 5); std::cout << first.size() << ", " << first << std::endl; return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.