0

Suppose I have this function:

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

I am fairly certain that this is defined behavior (as long as don't expect the memory to look like any thing specific ... I think).

But now suppose I have another function:

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

Is the following defined?

class A { /* Members of A */ };

A a;
uint8_t array = toBytes(a);
A* anotherA = toType<A>(array);
melpomene
  • 84,125
  • 8
  • 85
  • 148
DarthRubik
  • 3,927
  • 1
  • 18
  • 54

1 Answers1

1

I think it's undefined due to alignment issues. new uint8_t[sizeof(T)]; doesn't necessarily return memory that is suitably aligned for T.

melpomene
  • 84,125
  • 8
  • 85
  • 148
  • Dynamic memory (as returned by new) is alligned to any type.- see http://stackoverflow.com/questions/506518/is-there-any-guarantee-of-alignment-of-address-return-by-cs-new-operation – PiotrNycz Jun 25 '16 at 13:57