简体   繁体   English

reinterpret_cast与static_cast在标准布局类型中写入字节?

[英]reinterpret_cast vs. static_cast for writing bytes in standard-layout types?

I need to write to individual bytes of some integer types. 我需要写一些整数类型的单个字节。 Should I used reinterpret_cast , or should I use static_cast via void* ? 我应该使用reinterpret_cast ,还是应该通过void*使用static_cast

(a) (一个)

unsigned short v16;
char* p = static_cast<char*>(static_cast<void*>(&v16));
p[1] = ... some char value
p[0] = ... some char value

or (b) 或(b)

unsigned short v16;
char* p = reinterpret_cast<char*>(&v16);
p[1] = ... some char value
p[0] = ... some char value

According to static_cast and reinterpret_cast for std::aligned_storage 's answer both should be equivalent -- 根据static_cast和reinterpret_cast对std :: aligned_storage回答都应该是等价的 -

-- if both T1 and T2 are standard-layout types and the alignment requirements of T2 are no stricter than those of T1 - 如果T1和T2都是标准布局类型,并且T2的对齐要求不比T1更严格

I'm leaning towards reinterpret_cast as that is essentially what I'm doing, isn't it? 我倾向于reinterpret_cast ,因为这基本上是我在做什么,不是吗?

Are there any other things to consider, specifically looking at Visual-C++ and VC8, the version we're currently compiling on? 还有其他需要考虑的事情,特别是我们正在编译的Visual-C ++和VC8版本吗? (x86 only atm.) (x86只有atm。)

In this case (converting object pointers), reinterpret_cast is identical to the two nested static_cast via void* 在这种情况下(转换对象指针), reinterpret_cast与两个嵌套的static_cast相同,通过void*

5.2.10 Reinterpret cast [expr.reinterpret.cast] 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)) . 7对象指针可以显式转换为不同类型的对象指针。当对象指针类型的prvalue v转换为对象指针类型“指向cv T的指针”时,结果为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. 将“指向T1的指针”类型的prvalue转换为“指向T2的指针”类型(其中T1和T2是对象类型,T2的对齐要求不比T1更严格)并返回其原始类型会产生原始类型指针值。

It is better to use reinterpret_cast to signal your intent here. 最好使用reinterpret_cast来表达您的意图

UPDATE : as mentioned in the comments, this was apparently added in C++11, although most C++98 compilers already supported it (see also this Q&A ) 更新 :如评论中所述,这显然是在C ++ 11中添加的,尽管大多数C ++ 98编译器已经支持它(参见此问答

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM