是否可以将无符号字符数组reinterpret_cast到仅包含C++中无符号字符成员的结构指针
Is it portable to reinterpret_cast unsigned char array to struct pointer containing only unsigned chars members in C++
我知道使用 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++只是在注释中暗示了含义,但它毕竟是"未定义"的词源。
相关文章:
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- C++中无符号字符溢出
- 使用无符号字符数组有效存储内存
- 在 std::无符号字符的向量处存储 int 的十六进制表示形式
- 如何在保持其值的同时将 c++ 无符号字符变量转换为 char 变量
- 从 std::vector<无符号字符>切片中提取 int?
- 将无符号字符的向量存储在数组中会给我 std::bad_alloc
- 使用 fopen 打开 .pak 文件并使该文件应用于 const 无符号字符* (C++)
- 库特无符号字符
- 寻找一种更好的方法来表示无符号字符数组
- C++ 无符号字符 *{varName};-> C#
- 如何返回/复制unique_ptr<无符号字符[]>的值?
- 将浮点数转换为无符号字符数组并打印出来
- 在函数中返回无符号字符数组,但不返回指针
- 如何在 C/C++ 中将无符号字符*转换为无符号字符数组?
- 如何返回实际值(在我的例子中是无符号字符数组)而不是来自 C++ 函数的指针?
- 如何将带有十六进制值的 std::string 转换为 std::vector<无符号字符>
- 无符号字符打印其 ASCII 值
- 字符数组到无符号字符 *
- 是否可以在 c++ 中将两位数保存在无符号字符中