Suppose I have a POD type like this:
struct A {
char a;
int b;
};
On my system, sizeof(A) == 8
, even though sizeof(char) == 1
and sizeof(b) == 4
. This means that the data structure has 3 unused bytes.
Now suppose we do
A x = ...;
A y =x;
Question:
Is it guaranteed that all 8 bytes of x
and y
will be identical, even those 3 unused ones?
Equivalently, if I transfer the underlying bytes of some A
objects to another program that does not understand their meaning or structure, and treats them as an array of 8 bytes, can that other program safely compare two A
s for equality?
Note: In an experiment with gcc 7, it appears that those bytes do get copied. I would like to know if this is guaranteed.
=
is only required to copy the members. It might or might not copy the padding." Second paragraph in the top answer. – Subbasementmemcpy
will copy it though, because it doesn't know about it. – Osememcpy()
. Another technique I’ve sometimes used in C is to set all the bytes of the structure to 0 withmemset()
, and then do your memberwise copy. Modern compilers have been able to optimize the redundant double writes away for more than a decade. – Headset