sp2danny
sp2danny

Reputation: 7687

clang & gcc interpret series of cast differently

The following:

#include <iostream>

int& addone(int& r) {
    return ++r;
}

int main() {
    std::cout << addone((int&)(int&&)7) << std::endl;
}

compiles, runs and prints 8, using clang, even with -Wall -Wextra -Werror -pedantic .
Using gcc however, it does not compile at all, not even with -fpermissive .

Which is correct here? (preferably with quote)

clang result here, gcc result here

Upvotes: 1

Views: 175

Answers (1)

eerorika
eerorika

Reputation: 238461

It appears that the first conversion is OK. You convert an integer literal - a prvalue - to an rvalue reference. This causes temporary materialization conversion:

[conv.rval] A prvalue of type T can be converted to an xvalue of type T. This conversion initializes a temporary object ([class.temporary]) of type T from the prvalue by evaluating the prvalue with the temporary object as its result object, and produces an xvalue denoting the temporary object.

Let us consider the conversion to lvalue reference:

[dcl.init.ref] 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 (does not apply, the expression is not an lvalue)

  • has a class type (does not apply, the type is int&&)

Otherwise, if the reference is an lvalue reference to a type that is not const-qualified or is volatile-qualified, the program is ill-formed. (applies)

It appears that the program is ill-formed. Lack of diagnostic from clang suggests a compiler bug.

Upvotes: 1

Related Questions