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.
For any object (other than a base-class subobject) of trivially copyable type
T
, whether or not the object holds a valid value of typeT
, the underlying bytes (1.7) making up the object can be copied into an array ofchar
orunsigned char
. If the content of the array ofchar
orunsigned char
is copied back into the object, the object shall subsequently hold its original value. [Example:#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
—end example ]
In general, yes. The only way things break is if you access the object after destroying the object and before the restitution of it's data:
memset(&o, 0, sizeof(o));
obj.doSomething(); <--- breaks
memcpy(&o, bytes, sizeof(o));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With