Modern C++ • C++20 baseline
std::string, std::string_view, and Text Boundaries
Use owning strings for stored text and views for temporary non-owning access.
std::string owns a sequence of characters and manages its lifetime. std::string_view refers to character storage owned elsewhere, so it must not outlive that storage. Neither type guarantees that arbitrary external bytes form valid Unicode; validate and decode text according to the format your application accepts.
Key points
- A view can dangle after its source string is destroyed or reallocated.
- Use string_view as a read-only parameter when the function does not need ownership.
Example
#include <iostream>
#include <string>
#include <string_view>
std::string_view first_word(std::string_view text) {
const auto end = text.find(' ');
return text.substr(0, end);
}
int main() {
const std::string phrase = "safe text handling";
std::cout << first_word(phrase) << '\n';
}
What to expect
safe
Practice exercise
Return a view into a local std::string from a function, observe the lifetime bug, and redesign the function safely.
Key idea: Views avoid copies only when the referenced storage is guaranteed to remain alive.