gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:37:48 26 4
gpt4 key购买 nike

我知道使用 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 的对象,因此它不可能有一个成员 to refer .

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

关于c++ - 是否可以将 reinterpret_cast unsigned char 数组移植为仅包含 C++ 中 unsigned chars 成员的结构指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58466406/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com