Why doesn't the STL string class have an overloaded char* operator built-in? Is there any specific reason for them to avoid it?
If there was one, then using the string class with C functions would become much more convenient.
I would like to know your views.
char* is a pointer to a character. char is a character. A string is not a character. A string is a sequence of characters.
This last part of the definition is important: all C-strings are char arrays, but not all char arrays are c-strings. C-strings of this form are called “string literals“: const char * str = "This is a string literal.
Use std::string when you need to store a value. Use const char * when you want maximum flexibility, as almost everything can be easily converted to or from one.
char* means a pointer to a character. In C strings are an array of characters terminated by the null character.
Following is the quote from Josuttis STL book:
However, there is no automatic type conversion from a string object to a C-string. This is for safety reasons to prevent unintended type conversions that result in strange behavior (type char* often has strange behavior) and ambiguities (for example, in an expression that combines a string and a C-string it would be possible to convert string into char* and vice versa). Instead, there are several ways to create or write/copy in a C-string, In particular, c_str() is provided to generate the value of a string as a C-string (as a character array that has '\0' as its last character).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With