c++castinglanguage-lawyerstatic-castconst-cast

Why is (int&)0 ill-formed?


According to [expr.cast]/4, a C-style cast tries the following casts in order:

  1. const_cast
  2. static_cast
  3. static_cast followed by const_cast
  4. reinterpret_cast
  5. reinterpret_cast followed by const_cast

The following cast is well-formed:

const_cast<int&>(static_cast<const int&>(0))

Yet both GCC and Clang reject the cast (int&)0. Why?


Solution

  • It is a bug in gcc and clang.

    According to CWG 909, the "straightforward interpretation of the wording" should be used when generating cast sequences for C-style casts; there, the first cast invokes a conversion operator, but there is no reason to think that it should be any different when the first cast is reference binding a temporary.

    I've posted a patch to the gcc mailing list, generated from this git branch, but it hasn't received any attention so far.