[cfe-dev] "Mutable base class": Operator to base class "will never be used"

John McCall rjmccall at apple.com
Tue Dec 21 11:57:50 PST 2010


On Dec 21, 2010, at 9:44 AM, Sebastian Redl wrote:

> 
> On 21.12.2010, at 14:45, Gustaf Räntilä wrote:
> 
>> Is there some part of the language saying that an operator to a
>> reference of a class which happens to be a base class, is not valid
>> (or rather valid but "not used")?
> 
> No, but the derived-to-base conversion takes precedence over user-defined conversions. The warning exists because a user-defined conversion from derived to base will never be used under normal circumstances, but the derived-to-base conversion will make code that appears to use it compile, which might not be what the programmer expects.
> 
> In your special case, though, I think Clang is wrong. There is no derived-to-base conversion that adds drops const, and const Derived isn't reference-compatible with non-const Base either, so those code paths shouldn't be taken.

You can't use an explicit conversion operator to convert between reference-related types.

C++0x [dcl.init.ref]p5:
  A reference to type “cv1 T1” is initialized by an expression of type “cv2 T2” as follows:
    If the reference is an lvalue reference and the initializer expression
      — is an lvalue (but is not a bit-field), and “cv1 T1” is reference-compatible with “cv2 T2,” or
      — has a class type (i.e., T2 is a class type), where T1 is not reference-related to T2, and can be implicitly converted to an lvalue of type “cv3 T3,” where “cv1 T1” is reference-compatible with “cv3 T3”
      [then bind the reference to the lvalue / operator result]
    Otherwise, the reference shall be an lvalue reference to a non-volatile const type (i.e., cv1 shall be const), or the reference shall be an rvalue reference and the initializer expression shall be an rvalue or have a function type. [followed by lots of cases and a description of how to do this]

Note in particular the condition on the clause permitting conversion operators (i.e. the second bullet).  This was a clarification in '0x.

John.



More information about the cfe-dev mailing list