Usually string_view
is used for function parameters like this:
void fval(std::string_view sv);
void fcref(std::string_view const &sv);
Which is better?
const reference is 8 bytes and string_view
is usually twice that, e.g. 16 bytes.
However, if not inlined or optimized away, const reference might have two indirections - one for the ref, second for the pointer inside.
How STL doing it?
So, frequently, you can pass string_view by reference and get away with it. But you should pass string_view by value, so that the compiler doesn't have to do those heroics on your behalf.
string_view is useful when you want to avoid unnecessary copies. String_views are less memory-intensive to construct and copy. The creation of string_view from literals does not require a dynamic allocation.
The std::string type is the main string datatype in standard C++ since 1998, but it was not always part of C++. From C, C++ inherited the convention of using null-terminated strings that are handled by a pointer to their first element, and a library of functions that manipulate such strings.
std::string class in C++ C++ has in its definition a way to represent a sequence of characters as an object of the class. This class is called std:: string. String class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character.
We usually pass string_view
s by value.
Examples from the C++20 draft:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With