This is more of a policy or a historical question. Why was it decided not to provide a const char * conversion for std::string? Were there a fear someone might do printf("%s", s) and believe it would automatically convert? Are there any open discussions on this issue?
The c_str() and strcpy() function in C++ C++ c_str() function along with C++ String strcpy() function can be used to convert a string to char array easily. The c_str() method represents the sequence of characters in an array of string followed by a null character ('\0'). It returns a null pointer to the string.
1. Using string::c_str function. We can easily get a const char* from the std::string in constant time with the help of the string::c_str function. The returned pointer is backed by the internal array used by the string object, and if the string object is modified, the returned pointer will also be invalidated.
1 Answer. Show activity on this post. string is an object meant to hold textual data (a string), and char* is a pointer to a block of memory that is meant to hold textual data (a string). A string "knows" its length, but a char* is just a pointer (to an array of characters) -- it has no length information.
The member function c_str() returns a pointer to a null-terminated character array, whose elements are the same as those contained in the string. This lets you use strings with functions that require a pointer to a conventional C-style character array.
Automatic casts are almost always evil. If there were a cast to const char *
, a std::string
could be also automatically cast to other pointer types and that could lead to hard to find bugs. There is the c_str()
method that returns const char *
so you can still achieve what you need. Also, the typecast is not logically correct - std::string
is not equivalent to const char *
.
The string class internally need not store the string with a terminating 0. In fact it doesn't even have to store them in contiguous memory if it didn't want to. Therefore an implicit cast doesn't make sense, since it may be a costly operation.
The c_str() function then gives you the c-string. Depending on how the library stores it internally this function may have to create a temporary. This temporary is only valid until you modify the string.
It is unfortunately however since a string could just been specified to be a c-string internally. This wouldn't lead to any loss of functionality and would allow an implicit conversion.
Edit The standard does basically imply the memory is contiguous (if accessed through data() or the [] operator), though it need not be internally, and certainly not null terminated. Likely all implementations store the 0 as well. If this were standardized then the implicit conversion could be safely defined.
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