c++ – Practical use of std::string_view


It's clear to me that std::string_view is a string with only a pointer and a length, no ownership, no memory management, and no even terminating null – and so it doesn't have a c_str() function. But I could not figure out (find an example) when it can be preferable or more convenient than std::string ? If you don't mind, please answer with an example.


The problem that std::string_view is a problem that pops up almost every second when dealing with std::string . When it comes to non-modifying operations on strings, 9 times out of 10 we don't need functions that operate on the entire string. We need more general functions: those that operate on some substring of a given std::string , i.e. with some subrange of characters within the string.

To do this, of course, you can pre-allocate the substring of interest to us from std::string , for example, by calling substr , with the formation of a separate object of type std::string . And then work with the selected substring. But creating a substring as a separate std::string object is extremely inefficient and wasteful. This is where std::string_view comes in, which is a "virtual window" into an existing string. Those. std::string_view implements a virtual selection of a substring in a string, without additional memory allocation and data copying.

In fact, the general rule is that there should be almost no functions in your program with a parameter of type const std::string & . Almost all such functions should accept exactly const std::string_view & or std::string_view . That is, all the functionality of non-modifying string processing must be implemented in terms of std::string_view . And you can bind this std::string_view to the entire string, and to any of its substrings. This allows us to unify const string and substring processing without extra performance and resource overhead.

The fact that std::string_view can be "attached" not only to std::string strings, but also to regular C strings is another valuable additional functionality of std::string_view . That is, std::string_view allows us not only to unify strings with substrings, but also to unify the constant processing of std::string strings with C-strings.

Scroll to Top