Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do the padding bytes of a POD type get copied?

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 As 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.

like image 600
Szabolcs Avatar asked Oct 22 '17 14:10

Szabolcs


2 Answers

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.

like image 116
Baum mit Augen Avatar answered Oct 17 '22 07:10

Baum mit Augen


It's not authoritative, but cppreference's entry for std::memcmp suggests that the padding bytes may differ:

memcmp() between two objects of type struct{char c; int n;} will compare the padding bytes whose values may differ when the values of c and n are the same

like image 23
Tristan Brindle Avatar answered Oct 17 '22 08:10

Tristan Brindle