繁体   English   中英

是否可以将 reinterpret_cast unsigned char 数组移植到仅包含 C++ 中的 unsigned chars 成员的结构指针

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

我知道使用 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 进行了测试,没有添加任何填充,这有保证吗?

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

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

暂无
暂无

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

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