Search code examples
c++reinterpret-casttype-punning

Is this defined


Suppose I have a class A:

class A : virtual SomeOtherClass{
  //Stuff here
};

Suppose I have do this somewhere:

A thing;
alignas(A) uint8_t arr[sizeof(A)];
for (int x = 0; x < sizeof(A); x++)
{
  //Copy into array
  arr[x] = reinterpret_cast<uint8_t*>(&A)[x];
}

A* otherThing = reinterpret_cast<A*>(arr);

Is what I am doing here defined behavior, or am I killing myself in someway that I am unaware?


Solution

  • The shown code executes something that's equivalent to memcpy().

    As such, this is undefined behavior. Classes with virtual base classes are not trivially-copyable.