3 ms·
I would argue that you still have one string type, while the traditional C "string" type is actually an array of characters, or a pointer to an array of charact
by TimJYoung 8y ago
I would argue that you still have one string type, while the traditional C "string" type is actually an array of characters, or a pointer to an array of characters. :-)
Re: snprintf - yes I saw that and it definitely does do most of the heavy lifting, but it still is something that the developer needs to handle manually (I know, I know, not everyone should be using C...).
- vortico 8y agoNo, char* is definitely a string type. By having another one, that would be two. Believe me, working with C and C++ code and converting back and forth between std::string and char* is a nightmare. Let's not design that into the language itself.
- TimJYoung 8y agoIn C++, can't you just get a reference to the first character in the std::string and use it like a C-style string ?
- jcranmer 8y agostd::string isn't null-terminated. You need to use .c_str(), which allocates a copy that is destroyed when the string is changed (or is destructed).
- TimJYoung 8y agoAhh, yes, forgot about that - thanks !
- thestoicattack 8y agoIt seems[1] that since C++11 .data() and .c_str() are the same function. c_str() is also documented as having constant complexity. If it made a copy, wouldn't it have to be linear? [1] https://en.cppreference.com/w/cpp/string/basic_string/data https://en.cppreference.com/w/cpp/string/basic_string/data
- gpderetta 8y agoYes. Allocating on demand was a legal implementation before c++11. No standard library made use of the option and the latitude was removed in c++11. I think it is still allowed to null terminate on demand.
- hermitdev 8y agoIt doesn't have to make a copy. std::string is always null-terminated as of C++11.
- vortico 8y agoIn practice, all modern C++ compilers and standard libraries just set a null character to the c_str()[len] position and reallocate the string if the capacity of the string buffer cannot contain the extra byte. It is never a linear operation unless you're working with old or niche C++ compilers. In C++11 this is required in the standard.
- vortico 8y agoYes, it is easy to go back and forth between std::string and char* using the std::string constructor and ::c_str(). The "nightmare" part is that when interacting with C from C++, you can never work with the internal std::string data, so you have to manage copies of buffers and copy it back into a std::string every single time you interact with C functions. It's really nasty to look at in large quantities.
- TimJYoung 8y agoAhhh, okay, now I see the objection. Object Pascal allows you to use them interchangeably as you see fit with simple typecasts.