C ++-用于原始指针的reinterpret_cast的安全性 [英] C++ - Safety of reinterpret_cast for pointer-to-primitives
本文介绍了C ++-用于原始指针的reinterpret_cast的安全性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在我正在评估的项目中遇到了一段代码,想知道以下类型的转换是否安全:
I've come across a piece of code in a project I'm evaluating, and wanted to know if the following cast is safe:
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
是否自动使这种类型的转换操作安全?
I know that with just simple C-style casting (ie: (unsigned long*)&data
) that this is asking for trouble. Does reinterpret_cast
automagically make this type of casting operating safe?
谢谢.
推荐答案
不,这并不安全:程序行为未定义.
No it is not safe: the program behaviour is undefined.
这是因为指针类型无关.
This is because the pointer types are unrelated.
这篇关于C ++-用于原始指针的reinterpret_cast的安全性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文