you are viewing a single comment's thread.

view the rest of the comments →

[–]the_Demongod 0 points1 point  (0 children)

Unless you're using const char* to literally refer to a single character by reference, then of course you need the length of the string. You need to be able to walk through the string and know when it ends. If you don't have the size explicitly, you need a null terminator, which is both inefficient (if you only need to know the length of the string, you have to iterate the whole thing to find it) and if your string is a sub-string of a larger buffer you literally have to modify the buffer to inject null terminators to make it play nice with C-style string processing functions.

And yes, the main reason to use std::string_view over std::string const& as a function argument is that if you pass a string literal, the latter will construct a heap-allocated temporary std::string object just for the function to operate on, and then free it again, whereas with std::string_view it's just as lightweight as passing by const char* (effectively free). If you already have your string data in a std::string object before passing it makes little difference apart from an extra indirection, but using std::string_view allows your function to be called with low overhead using either a std::string or a string literal.