【发布时间】:2016-09-30 15:31:54
【问题描述】:
uint8_t* buf1;
...
const signed char* buf2 = static_cast<const signed char*>(buf1);
从类型 'uint8_t* {aka unsigned char*}' 到类型的无效 static_cast 'const 有符号字符*'
c-style-cast: (const signed char*) 工作正常
在这种情况下使用 c-style-cast 与 static_cast 有什么危险吗?
【问题讨论】:
-
好吧,定义“危险”。它是合法的。
-
static_cast 错误提示这不是安全操作,为什么 static_cast 失败?
-
因为你需要
reinterpret_cast -
No
static_cast告诉你它不能投射它,并不是说投射它很危险,你需要在这里使用reinterpret_cast,它会失败,因为签名和未签名的字符不同类型 -
因为
static_cast不能在指向不同类型的指针之间进行转换(除了void*)。您可以为此使用reinterpret_cast。操作是否安全取决于输入来自何处以及您正在使用它做什么。从语言的角度来看,这当然是合法的。