0

GCC produces warning when compiling the following code:

void* const & cast(int* const &ptr)
{
    return static_cast<void* const &>(ptr);
}

The warning is "returning reference to temporary" (coliru).

Clang compiles the code without warnings (coliru).

Which compiler is right? And why is reference converted to temporary?

Also note that changing static_cast to reinterpret_cast fixes the warning (coliru).

anton_rh
  • 8,226
  • 7
  • 45
  • 73
  • Handy reading: [Regular cast vs. static_cast vs. dynamic_cast](https://stackoverflow.com/questions/28002) – user4581301 Jun 25 '21 at 20:00
  • For this function _not_ to return a reference to a temporary, one would need to count on the parameter being _reinterpreted_. That would have to be the intention of the author. – Drew Dormann Jun 25 '21 at 20:04
  • 1
    Note: A lack of a warning doesn't necessarily mean code will work. the C++ Standard is full of "No diagnostic required"s. – user4581301 Jun 25 '21 at 20:10
  • "converts reference to temporary" technically it doesn't, because an expression cannot have a reference type. – n. m. could be an AI Jun 25 '21 at 20:21

1 Answers1

3

Clang 12 here gives me a similar warning. The one you linked to is probably outdated.

The code is broken, you return a dangling reference.

Unlike reinterpret_cast, the static_cast will refuse to reinterpret the reference. Instead it will construct a temporary of type void *1 from the original pointer, and form a reference to it (which is allowed, since the reference is const).

Note that performing a reinterpret_cast instead, and then reading/writing to the resulting reference, violates strict aliasing and causes undefined behavior.


1 I think it's a void * instead of void *const because of [expr.type]/2.

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207