Learn C++
#include "arrayspointers/string_view.hpp"

Non-Owning Views with string_view in C++

//concept

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.

//how it works
1

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.

2

Accept everything readable

void f(std::string_view s) takes std::string, literals, and other views alike — one signature replaces overload sets.

3

Substring without copying

v.substr(0, 5) and v.remove_prefix(3) carve views in O(1) — tokenizers that never allocate.

4

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.

//example
#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;
}
Output
5, hello
1The view borrows text's first five characters — no characters copied, no string constructed.
2size() reports 5 from the stored length, and streaming prints exactly the windowed range.
3text still owns everything; the view vanishes with no cleanup when it goes out of scope.
//use cases
Parser and splitter functions that must not allocate per token
Read-only string parameters accepting literals and strings uniformly
Zero-copy prefixes, suffixes, and trims via remove_prefix/remove_suffix
Auditing view lifetimes so no view outlives its owner's storage

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.