What are the dangers of std::string_view?
Short answer
Because string_view doesn't own its data, it dangles if the underlying string is destroyed or modified (e.g., a view of a temporary, or of a std::string that reallocates). You must ensure the referenced data outlives the view.
Advertisement
AModel answer
Because string_view doesn't own its data, it dangles if the underlying string is destroyed or modified (e.g., a view of a temporary, or of a std::string that reallocates). You must ensure the referenced data outlives the view. Also, string_view isn't guaranteed null-terminated, so don't pass its data() to C APIs expecting a null terminator.
std::string_view v = std::string("temp"); // dangles: temporary destroyedReal-world example
A string_view returned from a function referencing a local string dangles and reads freed memory.
Likely follow-ups
- Why can a string_view dangle? | Is string_view null-terminated?
Related topics