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

Mar*_* Ba 9 c++ reinterpret-cast visual-c++-2005 standard-layout c++11

我需要写一些整数类型的单个字节.我应该使用reinterpret_cast,还是应该使用static_castvia void*

(一个)

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

或(b)

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

根据static_cast和reinterpret_cast对std :: aligned_storage回答都应该是等价的 -

- 如果T1和T2都是标准布局类型,并且T2的对齐要求不比T1更严格

我倾向于reinterpret_cast基本上我在做什么,不是吗?

还有其他需要考虑的事情,特别是我们正在编译的Visual-C++和VC8版本吗?(x86只有atm.)

Tem*_*Rex 13

在这种情况下(转换对象指针),reinterpret_cast与两个嵌套的static_castvia 相同void*

5.2.10重新解释强制转换[expr.reinterpret.cast]

7对象指针可以显式转换为不同类型的对象指针.当对象指针类型的prvalue v转换为对象指针类型"指向cv T的指针"时,结果为 static_cast<cv T*>(static_cast<cv void*>(v)).将"指向T1的指针"类型的prvalue转换为"指向T2的指针"类型(其中T1和T2是对象类型,T2的对齐要求不比T1更严格)并返回其原始类型会产生原始类型指针值.

最好用这个reinterpret_cast来表达你的意图.

更新:如评论中所述,这显然是在C++ 11中添加的,尽管大多数C++ 98编译器已经支持它(参见此问答)