Undesirable cast being called in const casting (C++)

Martin v. Loewis martin@mira.isdn.cs.tu-berlin.de
Sun Oct 31 23:03:00 GMT 1999


> Exploring more, I found that gcc seems to be doing undesirable cast
> sequence in a case where there is a cast operation that for a const
> object, but no cast operation for a non-const object.

Thanks for your bug report. There is no bug in the compiler. It
exactly follows the ISO C++ standard, which clearly defines what
conversions should occur under what circumstances.

In some cases, these conversions seem to confuse users. In these
cases, the compiler issues a warning indicating that the conversion
might be confusing. You have encountered a common case.

> The cast "(const char*) foo" seems to be causing the following sequence
> to be used:
> 
>   (const char*)(((char*)foo)
> 
> when I really think the following is preferable even not knowing the cost
> of the casts:
> 
>   (const char*)((const hg_string)foo)
> 
> It would seem much more optimal to go for the const object cast first
> and then the (const char*) operator. Changing a non-const object to
> a const-object should always be an efficient operation, where as
> the cost of the operators is not known.

In either case, the compiler invokes a user-defined conversion
operator, and a qualification conversion (i.e. from non-const to
const). Right?

Criteria for selecting one over the other are not based on "costs",
since the compiler cannot know what "cost" an operator has (as you
indicate). Instead, a user-defined conversion sequence is "better"
than another one, if the conversions for the arguments are "better".

Both operators have one parameter, the argument is "hg_string" in both
cases. For the non-const conversion operator, the argument only
requires the "identity conversion", which is "better" than the
qualification conversion required for the const-operator. Thus, the
compiler has to select the non-const operator.

> Perhaps this is in the C++ standard? I do not know. If so, it seems
> like a very wierd thing. It would be nice to be able to at least
> turn of this behavior with a flag like -fcast-const-first or
> something.

The behaviour is mandated by the C++ standard, and g++ tries to follow
that as closely as possible. So, the compiler won't change the
rules. At best, there might be an option to suppress the warning.

Regards,
Martin



More information about the Gcc-bugs mailing list