Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass std::string_view by value or by const reference

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?

like image 663
Nick Avatar asked Oct 15 '19 14:10

Nick


People also ask

Should string_view be passed by reference?

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.

When should you use string_view?

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.

What is std :: string&?

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.

What is std :: string& in C ++?

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.


1 Answers

We usually pass string_views by value.

Examples from the C++20 draft:

  • Formatting
  • Time Zone Lookup
like image 200
Marshall Clow Avatar answered Oct 04 '22 02:10

Marshall Clow