This is the mail archive of the gcc@gcc.gnu.org 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]

Re: How to disable incorrect conversion ?


> If you would  look on this problem, please, contact with me.

Ruslan,

Here is a stripped-down version of the code you sent me which still
produces a warning:

class CORBA_String_var
{
    char* ptr_;

public:
    operator char*&() { return ptr_; }
    operator const char*() const { return ptr_; }
};
 

void message(const char*);

void f()
{
    CORBA_String_var s;
    message(s);
}

v.cc: In function `void f()':
v.cc:17: warning: choosing `CORBA_String_var::operator char *&()' over `CORBA_String_var::operator const char *() const'
v.cc:17: warning:   for conversion from `CORBA_String_var' to `const char *'
v.cc:17: warning:   because conversion sequence for `this' argument is better

Is this the problem you are talking about? If so, the compiler is right:
This call expands to

   char*& tmp = s.operator char*& ();
   message ((char*)tmp);

This is a user-defined conversion sequence. Therefore, the compiler
must do overload resolution for the conversion candidates. There are
two candidates, one expecting a "CORBA_String_var&", the other one
"const CORBA_String_var&", and the actual argument (i.e. *this) is
of lvalue type CORBA_String_var.

The identity conversion of this is better than the qualification
conversion in this case, so the compiler choses (rightly) the
non-const converter. It then ends up with a char*&, which gets
standard-converted to const char* as an argument to message.

If you want the const version to be called, you'd have to make s a
const object. I cannot see why you would want to do this, though,
since both conversion operators have identical implementations.

Hope this helps,
Martin


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