我在评估的项目中遇到了一段代码,想知道以下转换是否安全:
void func(unsigned long* input);
...
int data = 42;
func(reinterpret_cast<unsigned long*>(&data));
// Casting to remove compiler warnings about data type not matching type expected
我知道仅使用简单的 C 风格转换(即:(unsigned long*)&data
)这是自找麻烦。 reinterpret_cast
会自动使这种类型的转换操作安全吗?
谢谢。
最佳答案
不,这不安全:程序行为未定义。
这是因为指针类型不相关。
关于C++ - 指向基元的指针的 reinterpret_cast 的安全性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30714771/