jeudi 28 novembre 2019

Is this a good practice to replace 'const std::string &' with 'std::string_view' or just 'std::string'?

I was prefer const std::string & always when I need to play with std::strings. But recently, I suddenly noticed that there's no need to use const std::string & at all. The std::string_view will do better for read-only strings, and just std::string with move will do better for otherwise(setting string fields, etc).

// Read-only string example
bool foo(std::string_view bar) {
    return bar == "baz";
}
// Non read-only string example
void MyClass::foo(std::string bar) {
    this->baz = std::move(bar);
}

In above two cases, const std::string & is not optimal!

So I decided to remove all const std::string &s and replace these with one of them. So my question is :

  1. Will there any situation that const std::string & do better?
  2. If no, will I still need const std::string &?

Thank you.

Aucun commentaire:

Enregistrer un commentaire