其他分享
首页 > 其他分享> > c – reinterpret_cast到函数指针

c – reinterpret_cast到函数指针

作者:互联网

我用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?
}

首先,为什么允许这样的reinterpret_cast转换?我认为这种转变是不正确的.

解决方法:

The standard(C11§5.2.10/ 6)说

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.

所以它是未定义的行为.

标签:reinterpret-cast,c
来源: https://codeday.me/bug/20190830/1769257.html