0

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.)

Zohar81
  • 4,554
  • 5
  • 29
  • 82

1 Answers1

1

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.

Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141
  • 1
    If you need to save the string, the signature should be std::string (no reference). You can the move the string into its new storage. Big advantage of a string_view is that it allows the caller to pass in parts of a string without copying. – doron Nov 18 '21 at 13:08
  • @doron sometimes yes, when you're constructing a string everytime, but not if you might set a string. In that case you want a `std::string const&` and copy. – Guillaume Racicot Nov 18 '21 at 13:14
  • @doron see my answer: https://stackoverflow.com/a/69858529/2104697 – Guillaume Racicot Nov 18 '21 at 13:17
  • @GuillaumeRacicot, is it possible to give default value to string view in the function definition : i.e. `int func(std::string_view filename = "");` ? I guess not, while this is an option on the const string case, right ? – Zohar81 Nov 18 '21 at 13:44
  • @Zohar81 Of course this is an option with string views. But in either cases, you should use `int func(std::string const& filename = {});` or `int func(std::string_view filename = {});` which generates [smaller assembly *and* is faster](https://godbolt.org/z/dqTWGzj3K) – Guillaume Racicot Nov 18 '21 at 13:58
  • @Zohar81 Here's the same with string views: https://godbolt.org/z/vj46WvYP6 – Guillaume Racicot Nov 18 '21 at 14:00