St.*_*rio 5 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?
}
Run Code Online (Sandbox Code Playgroud)
首先,为什么reinterpret_cast允许这种转换?我认为这种转换是不正确的。
标准(C++11 §5.2.10/6) 说
指向函数的指针可以显式转换为指向不同类型函数的指针。通过指向与函数定义中使用的类型不同的函数类型的指针调用函数的效果是未定义的。除了将“指向 T1 的指针”类型的纯右值转换为“指向 T2 的指针”类型(其中 T1 和 T2 是函数类型)并返回其原始类型会产生原始指针值之外,这种指针转换的结果是未指定的.
所以这是未定义的行为。