tau*_*ran 3 c++ pointers casting
谁可以给我解释一下这个:
char* a;
unsigned char* b;
b = a;
// error: invalid conversion from ‘char*’ to ‘unsigned char*’
b = static_cast<unsigned char*>(a);
// error: invalid static_cast from type ‘char*’ to type ‘unsigned char*’
b = static_cast<unsigned char*>(static_cast<void*>(a));
// everything is fine
Run Code Online (Sandbox Code Playgroud)
2和3之间的区别是什么?如果将3的方法用于其他(更复杂的)类型,是否存在任何陷阱?
[编辑]有些人提到糟糕的设计等...
这个简单的例子来自一个图像库,它给出了指向图像数据的指针char*.显然,图像强度始终是正的,因此我需要将其解释为unsigned char数据.
static_cast<void*>消除类型检查的目的,因为你说它现在指向"你不知道的类型".然后编译器必须信任你,当你说static_cast<unsigned char*>新的void*时候,他只会尝试按照你明确的要求完成他的工作.
reinterpret_cast<>如果你真的必须在这里使用演员阵容,你最好使用(因为这里显示设计问题是显而易见的).
您的第三种方法是有效的,因为C++允许将void指针转换为T*via static_cast(然后再返回),但出于安全原因,它对其他指针类型的限制更多.char并且unsigned char是两种不同的类型.这需要一个reinterpret_cast.
| 归档时间: |
|
| 查看次数: |
5526 次 |
| 最近记录: |