Pitfalls and Lifetimes
Avoid dangling views.
Views Do Not Own
A string_view only points at characters owned elsewhere. If that storage disappears, the view dangles, accessing it is undefined behavior.
Dangling from a Temporary
Binding a view to a temporary std::string is dangerous: the temporary dies at the end of the statement, leaving the view pointing at freed memory.
#include <string>
#include <string_view>
std::string make() { return "temp"; }
int main() {
std::string_view sv = make(); // dangles immediately
// using sv here is undefined behavior
(void)sv;
}All lessons in this course
- Why string_view
- Creating Views
- Pitfalls and Lifetimes
- String Algorithms