Reputation:
As the title, I have two expressions:
int&& a = const_cast<int&&>(int{10});
int&& a = const_cast<int&&>(10);
The first compiling passed, but second not. Why is this happening?
In my view, it's because 10 is a literal and int{10} is a unamed variable. Is it?
Upvotes: 8
Views: 237
Reputation: 62603
The only reason why your first conversion passed is a bug in g++. Neither code is legal, and both clang and icc reject it.
They even give a good message:
error: the operand of a const_cast to an rvalue reference type cannot be a non-class prvalue
This does make sense, since both 10
and int{10}
are prvalues, and you can not bind a reference directly to prvalue. Instead, when references are initialized, compiler materializes the temporary variable and binds a reference to it. However, there are no rules for materializing temporary variables for const_cast
- so there is nothing to bind the reference to.
Upvotes: 6