TITLE: explicit and implicit conversions (Newsgroups: comp.std.c++, 11 Sep 96) KANZE: James Kanze ... Conversion of a C style string to a 'string' object is implicit (because of the corresponding constructor), conversion in the other direction requires the use of the explicit function string::c_str. PROBLEM: Kresimir Fresl Why is this so? As far as I can remember, this question occured few times in this newsgroup (and, maybe, in c.l.c++ and/or c.l.c++.moderated), but I never found a satisfying answer. KANZE: kanze@lts.sel.alcatel.de (James Kanze US/ESC 60/3/141 #40763) There are two aspects: 1. Both the implicit conversion and the explicit function (c_str) are dangerous in the sense that they return a pointer to part of the internal representation. This pointer may be invalidated by any non-const function of the object, including the destructor. 2. A conversion operator can be called implicitly, without appearing in the code. It is thus extremely easy for the conversion operator to be called unknowingly by the programmer. The explicit function cannot be called unknowingly, but must be explicitly requested by the programmer. Thus, for example, some current code contains the following: char const* f() ; char const* p = f() ; This is perfectly legal, and works. As part of a policy of continual improvement, however, the declaration of f() (in a header file, of course) is changed to: string f() ; I think that most people would agree that this is a reasonable evolution. Note, however, that the return value of f is a temporary, which will be destructed at the end of the enclosing full expression. So what happens with the above code: 1. If there is an implicit conversion operator string::operator char const*(), the above code is syntactically correct, and compiles without error. At run-time, p contains an invalid pointer (undefined behavior). It is not hard to imagine implementations/scenarios where the code will still work "most of the time." The resulting error can be extremely difficult to track down. 2. If there is no implicit conversion operator, the compiler will generate an error. The programmer is required to adapt his code so that it will work. Obviously, in this case, just calling c_str will *NOT* make the code work. Depending on other constraints (schedule, etc.), he will either rework his code completely, in order to use string, or he will declare a temporary with the same lifetime as p, assign the results of f to that, and then call c_str on that temporary. Either way, the resulting program is correct, and does not invoke undefined behavior.