struct的unsigned char别名

时间:2016-06-25 13:14:21

标签: c++ templates type-punning

假设我有这个功能:

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

1 个答案:

答案 0 :(得分:1)

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