This is purely hypothetical, but I’m not sure whether the following code will result in undefined behavior according to the C++ spec. I’d like to make a copy of the bytes in an object, blast the object by overwriting it with zeros, then copy the old bytes back. Can I do so without causing undefined behavior?
Sample code:
NonPODType o;
char bytes[sizeof(o)];
memcpy(bytes, &o, sizeof(o));
memset(&o, 0, sizeof(o));
memcpy(&o, bytes, sizeof(o));
In general, no. There’s an explicit guarantee that this works for trivially copyable types on §3.9/2, but there’s no such thing for other types.