Item 39. Automatic Conversions
Difficulty: 4
Automatic conversions
from one type to another can be extremely convenient. This Item
covers a typical example to illustrate why they're also extremely
dangerous.
The standard C++ string has no implicit
conversion to a const char*. Should it?
It is often useful to be able to access a
string as a C-style const char*. Indeed,
string has a member function c_str() to allow
just that, by giving access to a const char*. Here's the
difference in client code:
string s1("hello"), s2("world");
strcmp( s1, s2 ); // 1 (error)
strcmp( s1.c_str(), s2.c_str() ) // 2 (ok)
It would certainly be nice to do #1, but #1 is
an error because strcmp requires two pointers and there's
no automatic conversion from string to const
char*. Number 2 is okay, but it's longer to write because we
have to call c_str() explicitly.
So this Item's question really boils down to:
Wouldn't it be better if we could just write #1?
|