Why Don’t You Use String Views Instead of Passing strings by const&?
8 points by raymii
8 points by raymii
I talked about the same thing yesterday on Mastodon. IMO, if passing to C APIs is the only use case, I would just use a pointer to a null-terminated string directly rather than const std::string&.
Yeah, I take const char * all the time in my C++ code because the string gets passed to system APIs.
Relatedly, I really wish Linux had APIs for pointer + size style strings in its syscalls. It's currently not really possible to make an efficient language where all strings and string views are pointer+size; you either end up with incredibly non-ergonomic IO or all IO functions which need to pass a string to the kernel have to first copy its parameter to a temporary buffer to ensure 0 termination.
It would make sense for C++ to have additional string view types which are defined to point to nul-terminated C strings. Rust has &CStr for this purpose, which doesn't necessarily force heap allocation like using &CString would.
(Of course, slicing for CStr is restricted to taking suffixes, so that's rarely useful, but it still gives the caller the freedom to use a pointer to CString contents, a pointer to a C string in a stack buffer, a pointer into a global static/constant, etc.)
Hmm, when I last worked on Qt5 code using const & QString a lot, https://doc.qt.io/qt-6/qstringview.html didn't exist yet and now I'm wondering if this has the same problem, although I guess the windows angle would be less... likely.
It’s impossible for a general purpose string_view class to guarantee that the data is null terminated without defeating the purpose of having a non-owning view class. The data() method would have to copy the bytes to append the null, and if it has to do this you may as well just use an owning std::string instead of a view.