Undesirable cast being called in const casting (C++)
Derek Ney
derek@hipgraphics.com
Thu Oct 7 08:40:00 GMT 1999
I recently started compiling with gcc-2.95 and noticed this odd error
message:
dumbtest.cc:17: warning: choosing `hg_string::operator char *()' over
`hg_string::operator const char *() const'
dumbtest.cc:17: warning: for conversion from `hg_string' to `const char *'
dumbtest.cc:17: warning: because conversion sequence for the argument is
better
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. Here is my test
program to illustrate:
#include <stdio.h>
class hg_string {
public:
hg_string(char* f) { p = f; };
operator const char*() const
{ printf("const char *\n"); return p; };
operator char*()
{ printf("non-const char *\n"); return p; };
private:
char *p;
};
void print(const char*);
void function(hg_string& foo)
{
printf("%s", (const char*) ((const hg_string)foo));
printf("%s", (const char*) foo);
}
main()
{
hg_string a("hello\n");
function(a);
}
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.
I got around this by defining a third cast operator:
operator const char*()
{ printf("const char *(non-const obj)\n"); return p; };
This gets called then when the object is not const. But this seems
rather redundant and inefficient (programming wise). 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.
-Thanks, Derek Ney
More information about the Gcc-bugs
mailing list