27 ms·
This guideline is basically banning the use of std::string. Having a string abstraction beyond C null-terminated string is a huge deal both for convenience and
by RcouF1uZ4gsC 2y ago
This guideline is basically banning the use of std::string.
Having a string abstraction beyond C null-terminated string is a huge deal both for convenience and for safety. It is super easy to get strings wrong in C.
This is also one of the reasons why printf won't work. You cannot pass a type like std::string to a variable args function.
- hot_gril 2y agoWas gonna say, this guide is too light on examples. So an example of string usage would be passing around null-terminated char arrays.
- humanrebar 2y agostd::string_view with %.*s as a string formatter work well enough if you're set on using printf.
- gpderetta 2y agoI have to use std::string_view with %.*s as a string formatter every day. It is an incredible pain. Of course the solution is getting rid of printf style formatting, not string_view.
- o11c 2y agoThe hardest part of passing `std::string` to `printf` was getting the macro to convince the pre-standard-C++11 compiler that it was `constexpr` enough so that `-Werror=format` would work. I found it was easiest to sometimes allocate a temporary, if the input wasn't known to be NUL-terminated.
- jeffbee 2y agoAre you suggesting printf("%.*s", static_cast<int>(sv.size()), sv.data()) ?
- humanrebar 2y agoWell, wrap it up in something more ergonomic, but it works. I'm usually putting strings into some sort of I/O API (like a logger) instead of hardcoding copies to stdout everywhere. https://stackoverflow.com/a/72575650 https://stackoverflow.com/a/72575650
- jeffbee 2y agoWrap it way up into something ergonomic and idiomatic, like fmt.
- humanrebar 2y agoSure. I do. But there are tradeoffs even then. Look at the error messages compared to printf for example.
- throw4023042q0 2y ago> This is also one of the reasons why printf won't work. You cannot pass a type like std::string to a variable args function. Can't you just call .c_str() on the std::string first to get to the null-terminated char array? https://cplusplus.com/reference/string/string/c_str/ https://cplusplus.com/reference/string/string/c_str/
- AnimalMuppet 2y agostd::string str; printf("%s\n", str.c_str());
- cmovq 2y agoI can understand banning it. It’s important to understand std::string is more of a string builder implementation, which is rarely what you want, but people treat it as the default way to handle strings in C++. Too often I have to fix code that makes liberal use of std::string, making copies and allocations everywhere for no apparent reason, when string_view or better const char* would do.