std::string_view
Work with string efficiently.
1. Basics
string_view
(which lives in <string_view> header) provides read-only access to existing strings (C-style string, std::string or string_view) without making a copy. It acts as an observer, allowing us to view and utilize the string’s contents without the need for duplication or alteration.
1.1 Initialize with different types of strings
1 |
|
1.2 Accept different types of strings as parameters
1 |
|
2. Use string_view safely
If you try the provided examples, you probably won’t see any compiler generated warnings. This is typically due to the absence of warning-related flags in the compilation command. Here is the compile command that I use.
1 | -std=c++20 -Wpedantic -Wall -Wextra -Wconversion -O3 -Werror |
2.1 std::string_view to std::string
C++ doesn’t allow implicit conversion from std::string_view
to std::string
to prevent expensive copy.
However, we can still achieve that by doing:
- Explicitly creating
std::string
withstd::string_view
initializer.
- Explicitly creating
- Using
static_cast
to convert astring_view
tostring
.
- Using
1 |
|
2.2 Dangling viewer
Make sure it always points to valid objects
1 |
|
2.3 Return std::string_view safely
Returning a std::string_view
is not suggested since local variables will be destroyed at the end of the function, leading to invalid string_view. However, we can still achieve that by:
- Returning C-style literals that exist for the entire program.
- Returning a function parameter of type
std::string_view
since it exists in the scope of the caller.
1 |
|
References
std::string_view