【发布时间】:2014-08-05 04:05:53
【问题描述】:
这是我为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 转换?我认为这样的转换是不正确的。
【问题讨论】:
-
C++ 允许你以许多有趣的方式射你的脚,如果你幸运的话,编译器会给你一个警告。但是,如果您以任何方式禁用警告或错误,例如使用
reinterpret_cast将一种类型转换为另一种(可能不兼容)类型,许多人会说您应该得到您应得的。 -
@JoachimPileborg 但是 5.2.10/1 说下面列出了可以使用 reinterpret_cast 显式执行的转换。无法使用 reinterpret_cast 显式执行其他转换。 5.2.10没有这样的转换。
标签: c++ reinterpret-cast