This patch series improves conformance to the C++ standard for C-style casts 
(explicit cast notation, [expr.cast]) in two scenarios.

First, as discussed in CWG 909 [1], a C-style cast may invoke a user-defined 
conversion (as a static_cast) followed by a const_cast; currently this is 
erroneously rejected, tracked in PR77465 [2].

Second, a C-style cast to non-const reference to arithmetic type can and thus 
should be interpreted as a static_cast reference binding to temporary followed 
by a const_cast; currently it is interpreted as a reinterpret_cast (possibly 
followed by const_cast). To the best of my knowledge this has not been reported 
as a defect; credit to Turtlefight on Stack Overflow [3] for analyzing the 
situation, drawing my attention to the above issues, and convincing me that my 
interpretation was correct. Note that C-style cast to /const/ arithmetic 
reference will already introduce a temporary; this patch only changes the 
behavior where the reference is to non-const.

Clearly there is the potential for miscompilation of existing code that assumes 
an incorrect interpretation (reinterpret_cast); a number of existing test cases 
are amended in this patch series. In consideration of this, I have checked 
bootstrap (on x86_64) with no new errors, and add a warning (to Wconversion) 
where a C-style cast to arithmetic reference introduces a temporary in a 
situation where the user may expect a reinterpret_cast (type-punning); this 
affects both the const (existing) and non-const case. Note that this change 
will not affect C code compiled as C++, since that code cannot contain 
user-defined conversions or references.

In this patch series,
* 1/3 - allow C-style cast to invoke user-defined conversion followed by 
const_cast, resolving PR77465; adds a test case and fixes existing test cases 
which expect this to be rejected
* 2/3 - allow C-style cast to non-const reference to arithmetic type to invoke 
static_cast reference binding to temporary followed by const_cast; adds a test 
case and fixes existing test cases which expect reinterpret_cast semantics
* 3/3 - add comprehensive test suite covering expr.cast scenarios, positive and 
negative.

1. http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#909
2. https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77465
3. https://stackoverflow.com/a/70400230/567292

Reply via email to