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 p
My feeling is that C++ is a strongly typed language and implicit type conversions break type-safety.
It can often bite you where the conversion happens at a point where you do not expect it and can make your code hard to debug.
Non-explicit constructors can have a similar effect and std::string itself does have an implicit constructor from const char *. In this case it is not necessarily a bad thing although it can lead to inefficient code.
Regarding your previous comments:
If they are equivalent then there is no difference (except for convenience) to use cast instead of the c_str() call
There is one very important difference: one is implicit whereas the other is explicit.
C++0x introduces the notion of explicit
cast operators, but until then they are implicit, meaning that it is never clear (when looking at the code) whether they will be used or not.
Implicit cast are bad, especially since they can be cascaded, leading to extremely obscure code.
Moreover, as already stated, there is here a problem of correctness. Because the pointer returned by c_str
is only valid as long as the string
object does not change, then you could find yourself with hard to find bugs. Consider:
void function()
{
std::map<int, char const*> map;
map[1] = boost::lexical_cast<std::string>(47);
std::cout << map[1] << std::endl; // CRASH here, if lucky...
}
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.