Starting in C++17, string view classes have been added to the standard library. Available with inclusion of the header <string_view>
, string views introduce a way of referring to a constant contiguous sequence of character-like objects. The first element of any such sequence is at position zero.
As the name suggests, a string view provides a way to view a string without having to incur the overhead that normally comes with typical string usage. That is, a string view is only meant to point to an existing string.
Any space occupied should only belong to the pointed to string, not the view.
Usage Example
Use std::string_view
whenever you need query a string without modifying it, for example:
#include <iostream>
#include <string>
auto get_string_length(const std::string &str) -> size_t
{
return str.length();
}
int main() {
std::cout << "String length is: " << get_string_length("001239283954ABC");
return 0;
}
Should be:
#include <iostream>
#include <string_view>
auto get_string_length(const std::string_view str) -> size_t
{
return str.length();
}
int main() {
std::cout << "String length is: " << get_string_length("001239283954ABC");
return 0;
}
Note the difference in the function parameter of get_string_length()
The difference seems trivial, however taking a closer look shows one benefit of the string_view
version (click to enlarge):
Notice the string allocation when using normal std::string
.
Using std::string_view
directly does a compile time calculation of the length without doing any allocation.
Benefits
std::string_view
is available to use with most of the common std::string
functionalities, such as substrings, find, compare amongst others .
The complexity of std::string_view is mostly O(1), whereas you might end up with O(n) for functions such as substr.
In addition to the common char
type, string_view also supports wchar_t
, char16_t
and char32_t
types
Caveats
One not nice thing about string_view is the question of lifetime; a string_view
is only valid while the string it is pointing to is in scope.
This means that great care has to be taken to avoid ending up with a dangling pointer.