Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace const const std::string by reference with std::string_view

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading