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.
The implicitly-defined copy/move constructor for a non-union class X performs a memberwise copy/move of its bases and members.
12.8/15 [class.copy] in N4141
The bit pattern in the padding bytes is thus allowed to differ.
It's not authoritative, but cppreference
's entry for std::memcmp
suggests that the padding bytes may differ:
memcmp()
between two objects of typestruct{char c; int n;}
will compare the padding bytes whose values may differ when the values ofc
andn
are the same
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