c++ - reinterpret_cast 与 static_cast 用于在标准布局类型中写入字节?

标签 c++ c++11 reinterpret-cast visual-c++-2005 standard-layout

我需要写入某些整数类型的单个字节。我应该使用 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_storageanswer两者应该是等价的——

-- 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/

相关文章:

c++ - 将 std::packaged_task 添加到现有线程?

c++ - 我可以举一个现实生活中的例子,其中通过 void* 进行强制转换而 reinterpret_cast 无效吗?

c++ - 何时使用 reinterpret_cast?

c++ - 删除烦人的突出显示 Netbeans 7.2 C++

c++ - 声明一个数组,包含 N 个指向函数的指针,返回指向函数的指针,返回指向字符的指针

c++ - C++中的函数名冲突

c++ - Auto 和 Void 的区别?

c++ - exe 可以小于其最大的声明缓冲区吗?

c++ - Variadic 模板在多个参数上给出错误

c++ - 当两个链接的 static_cast 可以完成它的工作时,为什么我们在 C++ 中有 reinterpret_cast?