c++c++17

Is there sense in using const std::string& arguments in C++17?


By getting string_view in C++17 we got cheap method of passing both std::string and char* to functions that do not take ownership of the string and avoid making temporary copies. By using std::string passed by value and std::move we get explicit and fast passing of string ownership for both r-value and l-value references.

My question is: is there any benefit in using const std::string& as any function parameter in new C++ standard?


Solution

  • I see two valid reasons to use const std::string &:

    1. You're dealing with another API that also takes const std::string &. Passing a string_view to that would require copying

    2. You need the string to be null-terminated, e.g. to pass a const char * to a C API. std::string_view isn't guaranteed to be null-terminated, and doesn't remember if it's null-terminated or not, so you'd have to copy the contents to ensure the terminator is there.

    The second problem is better solved by having separate view type for null-terminated strings. We're finally getting std::zstring_view in C++26 for this, but implementing one yourself is simple too (here's mine).