But now that I'm learning about std::string_view. I'm wondering if one should prefer passing a std::string_view over a const ref std::string: |
Yes.
Really, the choice depends on the semantics of the function and the class you're defining, but in general:
std::string_view is the replacement for
std::string when you don't own the string.
If the function parameter is a
const string&, you should prefer to change it to
string_view: you don't own the argument.
If you do own the string, then
std::string alone is the only decent choice. In the case of your class, the window probably owns its title, and so the member should just be a string.
If the window doesn't own its title, use
string_view. Note that
const char* was never an option, because a
std::string may contain zero bytes (zero byte as in
'\0') in the middle. This means that unless you record the size, you can't always retrieve the original string.
string_view is best in this case because it doesn't require an actual
std::string to exist. Just a sequence of
char. In particular, if you do this:
std::string_view v{"this string is too long for small-buffer optimization\n"};
There is no memory allocation - a performance benefit.
We might also consider
std::string const* and
std::string const&), but they require a string to exist. If you pair
char const* and a size, you've got something that works, just less useful and more dangerous.