我需要写入某些整数类型的单个字节。我应该使用 reinterpret_cast
,还是应该通过 void*
使用 static_cast
?
(一)
unsigned short v16;
char* p = static_cast<char*>(static_cast<void*>(&v16));
p[1] = ... some char value
p[0] = ... some char value
或(b)
unsigned short v16;
char* p = reinterpret_cast<char*>(&v16);
p[1] = ... some char value
p[0] = ... some char value
根据 static_cast and reinterpret_cast for std::aligned_storage的 answer两者应该是等价的——
-- if both T1 and T2 are standard-layout types and the alignment requirements of T2 are no stricter than those of T1
我倾向于reinterpret_cast
,因为本质上就是我正在做的,不是吗?
是否还有其他需要考虑的事情,特别是 Visual-C++ 和 VC8,我们目前正在编译的版本? (仅限 x86 atm。)
最佳答案
在这种情况下(转换对象指针),reinterpret_cast
与两个嵌套的 static_cast
相同通过void*
5.2.10 重新解释转换 [expr.reinterpret.cast]
7 An object pointer can be explicitly converted to an object pointer of a different type.72 When a prvalue v of object pointer type is converted to the object pointer type “pointer to cv T”, the result is
static_cast<cv T*>(static_cast<cv void*>(v))
. Converting a prvalue of type “pointer to T1” to the type “pointer to T2” (where T1 and T2 are object types and where the alignment requirements of T2 are no stricter than those of T1) and back to its original type yields the original pointer value.
最好用reinterpret_cast
在此处表明您的意图。
更新:如评论中所述,这显然是在 C++11 中添加的,尽管大多数 C++98 编译器已经支持它(另请参见 this Q&A)
关于c++ - reinterpret_cast 与 static_cast 用于在标准布局类型中写入字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24626972/