moving an object in memory using std::memcpy

c++, c++11

Solution

As long as they are is_trivially_copyable, it is safe.

§ 3.9.2

For any object (other than a base-class subobject) of trivially copyable type T, whether or not the object holds a valid value of type T, the underlying bytes (1.7) making up the object can be copied into an array of char or unsigned char.40 If the content of the array of char or unsigned char is copied back into the object, the object shall subsequently hold its original value.

#define N sizeof(T)
char buf[N];
T obj; // obj initialized to its original value
std::memcpy(buf, &obj, N); // between these two calls to std::memcpy,
                           // obj might be modified
std::memcpy(&obj, buf, N); // at this point, each subobject of obj of scalar type
                           // holds its original value

§ 3.9.3

For any trivially copyable type T, if two pointers to T point to distinct T objects obj1 and obj2, where neither obj1 nor obj2 is a base-class subobject, if the underlying bytes (1.7) making up obj1 are copied into obj2,41 obj2 shall subsequently hold the same value as obj1. [ Example:

T* t1p;
T* t2p;
    // provided that t2p points to an initialized object ...
std::memcpy(t1p, t2p, sizeof(T));
    // at this point, every subobject of trivially copyable type in *t1p contains
    // the same value as the corresponding subobject in *t2p

Problem

Is it allowed to move a class instance object from one location to another (for example, by using `std::memcpy` or `std::memove`? Assume both source and destination locations have the same alignment. Then casting the destination "object" into the type of the source object and calling into it. What part of the C++11 standard forbids this?

Original source