结构体的无符号字符别名

Unsigned char alias for struct

本文关键字:别名 字符 无符号 结构体      更新时间:2023-10-16

假设我有这个函数:

template<class T>
uint8_t* toBytes(T&& obj)
{
  uint8_t* array = new uint8_t[sizeof(T)];
  for (int x = 0; x < sizeof(T); x++)
  {
    array[x] = reinterpret_cast<uint8_t*>(&obj)[x];
  }
  return array;
}

我相当确定这是定义的行为(只要不期望内存看起来像任何特定的东西…我认为).

现在假设我有另一个函数:

template<class T>
T* toType(uint8_t* array)
{
  return reinterpret_cast<T*>(array);
}

是否定义了以下内容?

class A { /* Members of A */ };
A a;
uint8_t array = toBytes(a);
A* anotherA = toType<A>(array);

由于对齐问题,我认为它未定义。new uint8_t[sizeof(T)];不一定返回适合T对齐的内存