I l@ve RuBoard Previous Section Next Section

Solution

graphics/bulb_icon.gif

The question was: The standard C++ string has no implicit conversion to a const char*. Should it?

The answer is: No, with good reason.

It's almost always a good idea to avoid writing automatic conversions, either as conversion operators or as single-argument non-explicit constructors.[2] The main reasons that implicit conversions are unsafe in general are:

[2] This solution focuses on the usual problems of implicit conversions, but there are other reasons why a string class should not have a conversion to const char*. Here are a few citations to further discussions: Koenig A. and Moo B. Ruminations on C++ (Addison Wesley Longman, 1997), pages 290?92. Stroustrup, Bjarne. The Design and Evolution of C++ (Addison-Wesley, 1994), page 83.

  • Implicit conversions can interfere with overload resolution.

  • Implicit conversions can silently let "wrong" code compile cleanly.

If a string had an automatic conversion to const char*, that conversion could be implicitly called anywhere the compiler felt it was necessary. What this means is that you would get all sorts of subtle conversion problems梩he same ones you get into when you have non-explicit conversion constructors. It becomes far too easy to write code that looks right, is in fact not right and should fail, but by sheer coincidence will compile by doing something completely different from what was intended.

There are many good examples. Here's a simple one:



string s1, s2, s3; 


s1 = s2 - s3;   // oops, probably meant "+"


The subtraction is meaningless and should be wrong. If string had an implicit conversion to const char*, however, this code would compile cleanly because the compiler would silently convert both strings to const char*'s and then subtract those pointers.

Guideline

graphics/guideline_icon.gif

Avoid writing conversion operators. Avoid non-explicit constructors.


    I l@ve RuBoard Previous Section Next Section