This is the mail archive of the mailing list for the GCC project.

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

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

I recently started compiling with gcc-2.95 and noticed this odd error
message: warning: choosing `hg_string::operator char *()' over 
`hg_string::operator const char *() const' warning:   for conversion from `hg_string' to `const char *' warning:   because conversion sequence for the argument is 

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 {
        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; };
        char *p;

void print(const char*);

void function(hg_string& foo)
        printf("%s", (const char*) ((const hg_string)foo));
        printf("%s", (const char*) foo);

        hg_string a("hello\n");


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

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]