In C++03, for std::string class, c_str() and data() methods have a different behavior.
The first returns a null-terminated character array and the management of this last is totally dependent from the implementation. Indeed, c_str() could return a pointer to another pre-allocated buffer, which always contains a null-terminated string, but this is not mandatory. However, the complexity must be constant.
The second one simply returns the pointer to the internal buffer of std::string, which could be null-terminated, or not.
Thus, in C++03, you could guess that a cast operator to const char* is not a good idea. Indeed, the expected behavior, most of the time, is to have a null-terminated C-style string, but, as the implementation of c_str() could vary, there could be an hidden overhead behind the cast operator. In the other case, it could bring confusion if the cast operator returns the same resultat as data().
However, for C++11, c_str() and data() have the same behavior. c_str() returns a pointer to the std::string object internal buffer. A cast operator to const char* is no more ambiguous. Why this method is not present in std::string class in C++11 ?
Thanks !
c_strordatais more readable than an explicit cast and an implicit cast would cause so many problems.c_str()when you need aconst char*is boring. @chris: what kind of problems ?const char*, and I do not see what is the problem with that.Matt McNabbs neighborhood of thinking. Every class I've seen developed with casting operators winds up doing something unexpected in non-trivial code. stackoverflow.com/questions/492061/…