Why Don’t You Use String Views Instead of Passing strings by const&?

8 points by raymii


LesleyLai

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&.

tsion

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.)