The char * operator in the STL string class

Why doesn't the string class have an overloaded char * operator? Is there any specific reason to prevent them?

If he was alone, then using a string class with C functions would be much more convenient.

I would like to know your opinions.

+7
c ++ stl
source share
6 answers

The following is a quote from the Josuttis STL book:

However, there is no automatic type conversion from a string object to a C-string. This is for security reasons to prevent inadvertent type conversion, which leads to strange behavior (char * type often has strange behavior) and ambiguity (for example, an expression that concatenates a string and a C-string could convert the string to char * and Versa). Instead, there are several ways to create or write / copy to a C-string, in particular, c_str () is to generate a string value as a C-string (as a character an array that has "\ 0" as the last character).

+16
source share

You should always avoid translation operators, as they tend to introduce ambiguity into your code, which can only be resolved using other tricks, or, even worse, compile, but not do what you expect. The char * () operator would have many problems. For example:

string s = "hello"; strcpy( s, "some more text" ); 

will compile without warning, but compresses the string.

There may be a variant with a constant, but since the lines should (possibly) be copied for its implementation, this will have an undesirable hidden cost. The explicit function c_str () means that you should always indicate that you are really going to use const char *.

+12
source share

The specification of a string template deliberately allows for โ€œdisabledโ€ presentation of strings, where the entire contents of a string consists of several fragments. Such a representation does not allow easy conversion to char *.

However, the string template also provides the c_str method just for your purpose: what is wrong with using this method?

+5
source share

You can use c_str instead:

 string s("I like rice!"); const char* cstr = s.c_str(); 

I believe that in most cases you do not need char *, and it can work more conveniently with the string class itself.

+2
source share

By 1998-2002, this was a hot topic in C ++ forums. The main problem is the null terminator. Spec of std ::? String allows a null character as normal, but char * string does not.

+2
source share

If you need to interact with C-style functions, using std::vector<char> / <wchar_t> is often easier.

This is not so convenient, and, unfortunately, you cannot O (1) -load it with std::string (now that would be nice).

In this regard, I prefer the MFC / ATL CString interface, which has stricter performance guarantees, provides interoperability, and does not treat strings with a wide / unicode character as completely alien (but normal, the latter is somewhat platform specific).

0
source share

All Articles