简体   繁体   中英

reinterpret_cast to function pointer

There is the code that I've written for experiments with reinterpret_cast<T>

#include <iostream>
#include <cstdlib>

using std::cout;
using std::endl;

int foo()
{
    cout << "foo" << endl;
    return 0;
}

void (*bar)();
int main()
{

    bar = reinterpret_cast<void (*)()>(foo); //Convertion a function type to a pointer to function type
    bar(); //displays foo. Is it UB?
}

First of all why such reinterpret_cast convertion permitted? I thought such conversion is ill-formed.

The standard (C++11 §5.2.10/6) says

A pointer to a function can be explicitly converted to a pointer to a function of a different type. The effect of calling a function through a pointer to a function type that is not the same as the type used in the definition of the function is undefined. Except that converting a prvalue of type “pointer to T1” to the type “pointer to T2” (where T1 and T2 are function types) and back to its original type yields the original pointer value, the result of such a pointer conversion is unspecified.

So it is undefined behavior.

Formally calling via the pointer casted to different function type is Undefined Behavior (by C++11 §5.2.10/6).

In practice you're casting away a function result of type int , that would be returned in a register. So about the worst that can happen when you call via the casted pointer, is that contrary to the compiler's expectations a register has changed value.

Another practical consideration: C++ does not support casting between function and data pointers, but Posix effectively requires cast to void* and back to work OK. The C++ restriction is presumably in support of Harvard architecture machines, where instructions are not retrieved via the same bus and memory as ordinary data. But the Posix round-trip would presumably work also on such architecture, unless the data address space was much smaller than the instruction address space.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM