C++ - 指向原语指针的reinterpret_cast 的安全性

Clo*_*oud 1 c++ casting type-safety reinterpret-cast

我在正在评估的项目中遇到了一段代码,并想知道以下转换是否安全:

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
Run Code Online (Sandbox Code Playgroud)

我知道,仅使用简单的 C 风格转换(即:)(unsigned long*)&data,这是自找麻烦。是否reinterpret_cast自动使这种类型的铸造操作安全?

谢谢。

Bat*_*eba 5

不,它不安全:程序行为未定义。

这是因为指针类型不相关。