【问题标题】:Is it portable to reinterpret_cast unsigned char array to struct pointer containing only unsigned chars members in C++是否可以将 reinterpret_cast unsigned char 数组移植到 C++ 中仅包含 unsigned chars 成员的结构指针
【发布时间】:2020-02-16 08:51:18
【问题描述】:

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

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); 

但我的问题是针对只有 unsigned char 成员的结构

struct RGB
{
    unsigned char r;
    unsigned char g;
    unsigned char b;
};

unsigned char data[3];
RGB* rgbData = reinterpret_cast<RGB*>(data); 

在这种情况下,struct RGB 相当于 unsigned char[3],因此我假设不会有填充。我用g++和msvc测试过,没有加padding,有保证吗?

【问题讨论】:

  • 请注意,该结构可能有一些对齐/填充。
  • 使用 GCC,您可以通过 __attribute__((packed)) 强制不填充

标签: c++ struct casting


【解决方案1】:

虽然reinterpret_cast 是明确定义的(因为您可以安全地将reinterpret_cast 恢复为原始类型),但访问结构成员是未定义的行为 暗示:没有对象键入RGB,因此不能有to refer 所属的成员。

C 明确且规范地描述了标准将没有行为描述为未定义行为的情况; C++ 只是注释中的implies the implication,但它毕竟是“未定义”的词源。

【讨论】:

    猜你喜欢
    • 2012-11-16
    • 2013-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多