stl · high

std::string_view & Dangling

std::string_view is a lightweight, non-owning handle: a pointer to the first character plus a length. Building one and slicing it (substr, remove_prefix/suffix) copies nothing and never allocates — it just moves the pointer and length. The cost is lifetime: the view does not own or extend the storage, so viewing a temporary (a function returning std::string by value, or operator+ results) leaves a dangling pointer into freed memory. A view also tracks length, not termination, so a sub-view's .data() is not a C string. Use string_view for read-only parameters over storage that clearly outlives it; convert to std::string when you need ownership or null-termination.

🔑 Key line

std::string_view is a non-owning {pointer, size} window: slicing it is O(1) with no allocation, but it dangles the instant the underlying characters die (classically when you view a temporary), and a sub-view is not null-terminated, so never pass .data() to a C API expecting a NUL.

The code

std::string s = "Hello, interview!";
std::string_view sv = s; // non-owning {ptr,size} window — no copy
sv = sv.substr(7, 9); // "interview": just moves ptr/len, O(1)
std::string_view bad = make_name(); // DANGLING: temporary dies at the ;
std::string_view bad2 = name + "!"; // DANGLING: views a temporary string
// a sub-view is NOT guaranteed null-terminated:
puts(sv.data()); // BUG: reads past the 9-char window

What this lesson walks through

  1. 01A view is a {pointer, size}, not a string
  2. 02Slicing is free: just move ptr + len
  3. 03Dangling: viewing a temporary
  4. 04Dangling: concatenation makes a temporary
  5. 05A sub-view is not null-terminated
  6. 06Safe usage: outlive the view
  7. 07The view contract in one breath

std::string_view does not own characters. It is just a pointer to the first character plus a length. Constructing it from s copies no characters — it points straight into s's buffer.

See it animated — step by step, at your own pace

Unlock the full interactive walkthrough of std::string_view & Dangling and 100+ animated C++ interview lessons.

← Previous
Iterator Invalidation
Next →
std::variant & std::visit