6

I preferred 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.

AcrylicShrimp
  • 160
  • 2
  • 9
  • The view is also nicer when calling the function with a literal string as it doesn't need to construct a temporary `std::string` from it. Or is that what you meant by read only string? – Shawn Nov 29 '19 at 02:14
  • @Shawn I mean, `read-only string` is strings that are not get modified in a function. Yes, it can be created from literals, or reference of an existing string instance maybe. – AcrylicShrimp Nov 29 '19 at 02:19
  • 4
    @AcrylicShrimp, `std::string` holds a zero-terminated string, so the value returned by `c_str()` method can be passed directly to one of functions (espacially when dealing with c-functions) that expects a zero-terminated c-string as an input argument. Conversely this can not be done using the `std::string_view` solely (you need to create a buffer that will hold a zero-terminated c-string in this case). – Deedee Megadoodoo Nov 29 '19 at 04:41
  • @RealFresh But every `std::string_view` created by `std::string`s and string literals will be null-terminated, right? – AcrylicShrimp Nov 29 '19 at 05:05
  • 5
    Not if it's a view of a substring. – Shawn Nov 29 '19 at 05:25
  • 1
    What I still don't get (with `std::string_view`): For non-meta programming, where a function expects a `const std::string&` (and cannot be changed because it's third-party or just too much effort), a `std::string_view` has to be copied (and even explicitly) while a `std::string` would match perfectly. (New fancy features also have draw-backs if you are bound to a big, long-living code-base - my sad experience.) Or, did I overlook something? – Scheff's Cat Nov 29 '19 at 07:28
  • For the setter case, user might misuse it and so creates extra copy (`std::string s = f(); foo(s)` instead of `foo(std::move(s));`). Expecting `std::string&&` would force user to do the copy explicitly. – Jarod42 Nov 29 '19 at 09:23
  • I also want to know if we can remove all `const std::vector& v` and replace these with c++20 `span`. – 康桓瑋 Nov 29 '19 at 09:57

0 Answers0