2 ms·
C++'s std::string might as well be syntactic sugar on top of a std::vector<char> (due to significant similarities in implementation and API), with null-terminat
by vitus 2y ago
C++'s std::string might as well be syntactic sugar on top of a std::vector<char> (due to significant similarities in implementation and API), with null-termination by default for C interop. In general, in C++ you shouldn't be passing around null-terminated strings unless you're working with some legacy C API, at least without also passing the size of the string (unless you really like calling strlen, like that GTA5 code [0]), at which point you might as well pass const std::string& or std::string_view (which can be constructed transparently from a std::string).
Why do you say that std::string_view is more awkward to use as a result of being part of the stdlib?
[0] https://news.ycombinator.com/item?id=26296339 https://news.ycombinator.com/item?id=26296339
- flohofwoe 2y ago> Why do you say that std::string_view is more awkward to use as a result of being part of the stdlib? As far as I'm aware, the type of string literals in C++ is still a "raw" char pointer and not a string view. Also few libraries actually make use of std::string_view, while in Zig everything is built around strings as slices, from the language to the stdlib to 3rd party libs (easy to do of course in a new language ecosystem).
- vitus 2y ago> As far as I'm aware, the type of string literals in C++ is still a "raw" char pointer and not a string view. You can define a constexpr std::string_view with a literal if you so choose. And if you pass a string literal to a function that accepts a string_view, then the compiler has enough information to (and typically will) construct the string_view in constant time. (A sibling commenter also points out that you can use the sv suffix: https://en.cppreference.com/w/cpp/string/basic_string_view/operator%22%22sv https://en.cppreference.com/w/cpp/string/basic_string_view/o...) (Meanwhile, if you pass a string literal to a function that accepts const std::string&, then that will be a linear-time operation, as it copies that data since std::string owns its data. But with any amount of indirection, you'll end up with an implicit strlen call. So this is absolutely a pitfall.) > few libraries actually make use of std::string_view This is a fair point, as it's a relatively new addition to the language and by no means mandatory.
- dasyatidprime 2y agoThe first part is true for ‘normal’ string literals, but there's suffixed string literals since I think C++17: "foo"sv is a std::string_view if you have operator""sv from std::string_view_literals visible.
- account42 2y agoTechnically, C++ string literals are not pointers but arrays. Arrays can decay to pointers though.