Home > Mobile >  Replace const std::string passed by reference, with std::string_view
Replace const std::string passed by reference, with std::string_view

Time:11-18

I've got the following method which gets std::string as input argument.

int func(const std::string &filename);

From it's signature, the input type refers passed by reference (no copy is made) and shouldn't be changed (by the const prefix).

Would it be equivalent of using std::string_view instead, which is also used for read only ?

int func(std::string_view filename);

And if not, so in which aspect they're not similar (runtime, memory consumption, functionality, etc.)

CodePudding user response:

No it's not equivalent.

There are two cases where using std::string const& is a better alternative.

  1. You're calling a C function that expects null terminated strings. std::string_view has a data() function, but it might not be null terminated. In that case, receiving a std::string const& is a good idea.

  2. You need to save the string somewhere or you're calling a C function that expects a std::string const&. Sometimes they are function from libraries that would be undesirable to change.

All other cases would be better with std::string_view

There is also some key differences between a string view and a reference to a string.

First, you are passing by reference, not by value. The compiler has to reference it everytime it want to access the capacity, size or data.

Second, a string view don't use capacity, only a size and a data. It also means that loads can be omitted since you are passing it by value, as a local variable with limited scope.

  • Related