Mail Archives: djgpp/1999/07/13/22:51:13
On Tue, 13 Jul 1999 19:56:53 GMT, David Harmon <source AT netcom DOT com> wrote:
>On Tue, 13 Jul 1999 14:18:58 -0500 in comp.lang.c++, Mark Phillips
>>What's wrong with operator functions? Not that I disbelieve you, it's
>>just that I'm very unenlightened...
>
>It's not what's wrong with operator functions; it's what's wrong with
>implicit conversion operators. Unless you are the kind of person who
>never makes mistakes, the compiler will apply them in places where you
>may not expect it, where otherwise the compiler would have caught a type
>mismatch error for you.
Right. Some of these errors will be caught at compile time, but the
error messages will be very obscure and difficult to wade through.
Some errors will only show themselves at runtime. For example, suppose
that class String has a conversion to "const char *". Now consider
this typo
void f(const String& in) { String out=in+3; }
Maybe we meant to concatenate 'in' and "3". Or maybe we meant to
add atoi(in) and 3, then convert the result into a String. However,
there is no operator+(String,int). So the compiler converts 'in'
to "const char *" using the implicit conversion operator, then
converts 3 from int to size_t and calls operator+(pointer,size_t).
The effect is the same as this
void f(const String& in) { String out=&in[3]; }
This basically extracts a right substring of 'in'. And if 'in' is
3 chars or less, then we have a memory access violation. Because
the above code passes compilation, it's going to be very hard to
detect the error. The program is going to behave strange, and
we're not going to know where to look for the bug.
Accordingly, class std::string has no operator conversion. Instead
it has an explicit get function with a rather bizarre name
std::string::c_str() const.
--
----------------------------------
Siemel B. Naran (sbnaran AT uiuc DOT edu)
----------------------------------
- Raw text -