【发布时间】:2015-06-08 16:44:56
【问题描述】:
我在一个正在评估的项目中遇到了一段代码,想知道下面的演员表是否安全:
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 会自动使这种类型的铸造操作安全吗?
谢谢。
【问题讨论】:
-
为什么不是 &static_cast
(data)? -
@KABoissonneault 这样可以保证安全操作吗?我觉得这很明智。谢谢!
-
@KABoissonneault 您不能获取prvalue的地址。那不会编译。
-
@Barry Meh,然后首先将 static_cast
(这就是我在第一条评论中的意思)分配给局部变量,然后获取其地址
标签: c++ casting type-safety reinterpret-cast