Handle dangling string_view
How do I safely handle dangling std::string_view?
Handling dangling std::string_view safely is crucial because using a std::string_view that references deallocated memory leads to undefined behavior. Here are some best practices to avoid dangling std::string_view:
Ensure String Lifespan
Make sure the original string outlives the std::string_view. Avoid returning std::string_view from functions that create local strings:
#include <string_view>
std::string_view getStringView() {
std::string temp{"Hello"};
return std::string_view{temp};
}
int main() {
std::string_view view = getStringView();
}The above code is problematic because temp is destroyed when the function exits, leaving view dangling. Instead, return the std::string itself:
#include <string>
#include <string_view>
std::string getString() {
return std::string{"Hello"};
}
int main() {
std::string str = getString();
std::string_view view{str};
}Use String Literals
For static strings, use string literals, which have static storage duration:
#include <string_view>
int main() {
std::string_view view{"Hello, world"};
}Avoid Temporary Strings
When initializing a std::string_view, ensure it doesn't refer to a temporary string:
#include <string>
#include <string_view>
int main() {
using namespace std::string_literals;
std::string_view view{"Hello"s};
}Instead, use string literals or persistent strings:
#include <string_view>
int main() {
std::string_view view{"Hello"};
}By following these practices, you can avoid common pitfalls and ensure your std::string_view remains valid throughout its usage.
String Views
A practical introduction to string views, and why they should be the main way we pass strings to functions