Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why std::string hasn't const char* cast operator in C++11?

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 !

like image 353
AntiClimacus Avatar asked Oct 01 '22 04:10

AntiClimacus


1 Answers

Your question is fundamentally about the philosophy behind the design of the string class. I can but opine.

Why should string have a cast operator to const char*? Cast operators are syntactic sugar for other operations, and are truly needed only in unusual circumstances. Really, they are never needed -- you can always accomplish the same goal in another way.

string already does provide the means to interract with old C-style interfaces, via c_str and data. Adding a cast operator in to the mix doesn't add functionality and does add complexity to the class. Moreover, using a cast operator is always semantically murky. In call-site code, a cast such as with static_cast <const char*> is generally expected to be a compile-time operation. By performing this cast through run-time code, you ambiguate your code. It's not as clear. Because the expectations and reality aren't the same, it's much easier to misuse this run-time cast than the compile-time equivalent.

I would argue that there should not be an implicit conversion operator anywhere it's not truly needed; and it isn't here.

like image 163
John Dibling Avatar answered Oct 13 '22 00:10

John Dibling