Search code examples
c++gccclangstatic-cast

GCC converts reference to temporary when doing static_cast to void pointer reference


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).


Solution

  • 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.