Introduction to std::string_view/std::span
std::string_view
std::string_view
is imported in C++17.
It stores the address of a string and its length. In some cases, it can avoid the overhead of copying strings such as in the parameter of function void foo(const std::string&)
.
Note that it can only be used for reading, not writing.
1 |
|
Output:
1 |
|
std::span
std::span
is imported in C++20.
It’s similar to std::string_view
, and it describes a continuous sequence of memory. The most important thing is that it can be used instead of an array as a function argument, because when we use an array as a parameter (non-reference), it will degrade to a pointer, so we have to pass the length of the array additionally, which is a hassle.
1 |
|
References
Introduction to std::string_view/std::span
http://wasprime.github.io/Dev/C++/STL/Introduction-to-std-string-view-std-span/