Exceptions
Team LiB
Previous Section Next Section

Exceptions

When used sparingly and with care, implicit conversions can make calling code short and intuitive. The standard std::string defines an implicit constructor that takes a const char*. This works fine because the designers took some precautions:

  • There is no automatic conversion to const char*; that conversion is provided through two named functions, c_str and data.

  • All comparison operators defined for std::string (e.g., ==, !=, <) are overloaded to compare a const char* and a std::string in any order (see Item 29). This avoids the creation of hidden temporary variables.

Even so, there can still be some weirdness with overloaded functions:



void Display( int );


void Display( std::string );





Display( NULL );                     // calls Display(int)



This result might be surprising. (Incidentally, if it did call Display( std::string ), the code would have exhibited undefined behavior because it's illegal to construct a std::string from a null pointer, but its constructor isn't required to check for the null.)

    Team LiB
    Previous Section Next Section