C++

Strings & string_view

11 question(s)

Why should you avoid returning std::string_view to local data?

Intermediate
Returning a string_view that refers to a local std::string, a temporary, or a function parameter passed by value creates a dangling view once that data is destroyed at function return. Return an owning std::string (or ensure the referenced data has a longer lifetime) instead. string_view is safe to return only when it views data that outlives the call.
std::string_view bad() { std::string s="x"; return s; } // dangles
Real-world example A helper returning string_view into a local buffer produces garbage; returning std::string fixes it.

Common follow-ups: When is returning a string_view safe? | What should you return instead?

Memory Management Strings & string_view Strings & string_view