0Pricing
C++ Academy · Lesson

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

  1. Why string_view
  2. Creating Views
  3. Pitfalls and Lifetimes
  4. String Algorithms
← Back to C++ Academy