是否可以将无符号字符数组reinterpret_cast到仅包含C++中无符号字符成员的结构指针

Is it portable to reinterpret_cast unsigned char array to struct pointer containing only unsigned chars members in C++

本文关键字:字符 无符号 C++ 包含 成员 指针 结构 cast 数组 reinterpret 是否      更新时间:2023-10-16

我知道使用 reinterpret_cast 将无符号字符数组强制转换为结构指针可能会导致问题,因为不同系统上的字节填充和排序(如本例所示(

struct SomeData
{
unsigned char first;
int second;
};
unsigned char data[5];
// SomeData might be more than 5 bytes because of padding
// We can't be sure second is valid, because of bytes ordering
SomeData* someData = reinterpret_cast<SomeData*>(data); 

但我的问题是对于只有未签名字符成员的结构

struct RGB
{
unsigned char r;
unsigned char g;
unsigned char b;
};
unsigned char data[3];
RGB* rgbData = reinterpret_cast<RGB*>(data); 

在这种情况下,结构 RGB 相当于无符号字符[3],因此我认为不会有填充。我已经使用 g++ 和 msvc 进行了测试,但没有添加填充,这能保证吗?

虽然reinterpret_cast是明确定义的(因为您可以安全地reinterpret_cast回原始类型(,但访问结构成员是隐含的未定义行为:没有类型RGB的对象,因此不可能有可以引用的成员。

C 明确和规范地将标准没有行为描述为未定义行为的情况;C++只是在注释中暗示了含义,但它毕竟是"未定义"的词源。