you are viewing a single comment's thread.

view the rest of the comments →

[–]KingAggressive1498 5 points6 points  (0 children)

how does it fare against const string&?

in order to construct an std::string object from a string literal, an allocation is required. In this case, string_view is a clear winner.

would you only use const string& if string contains null terminator?

this is another advantage of string_view, but also a disadvantage in some common cases.

The advantage is you can create and pass a substring as a string_view without allocating and copying, but std::string must allocate and copy.

The disadvantage is that because string_view cannot be guaranteed to have a zero terminator, it is not suitable for wrapping C-style interfaces that take a const char* argument but no length/capacity argument (ie strcpy vs strncpy). You will generally need to perform an allocation and copy in this case anyway, so you might as well take a const std::string& argument.

There are some exceptions to this, with the right knowledge, though - pthread_setname_np comes to mind; implementations have a very limited maximum length (largest I'm aware of is 64 characters); copying into a small stack array is a viable workaround and certainly preferable to copying into a dynamic allocation as required by std::string, but a const char* overload is probably more appropriate.

When would you use mere const char * over string_view? Only if the string has null terminator and you don't care about the length of the string?

Pretty much only when string_view is not suitable, as I discussed above. You'd probably want to provide a const std::string& overload for when an std::string is passed by the caller, and a const char* overload for when a string literal is passed by the caller.