memcmp
compares the raw memory representation of two objects (what the standard calls their object representation). When
objects are not trivially copyable or contain padding, they could have different raw memory representations even though they store identical values.
So the result of memcmp
is not meaningful.
Padding refers to the insertion of additional bits into a structure or class to ensure proper alignment of its members in memory.
Trivially copyable types include:
- scalar types
- trivially copyable classes
- arrays of these types
A class is trivially copyable when:
- all its non-static data members and base classes are trivially copyable types,
- it has no virtual functions or base classes,
- its destructor is trival,
- and one or more of the following special member functions is trivial, and the rest are deleted: copy constructor, move constructor, copy
assignment operator, and move assignment operator.
Note: a default implementation is always considered trivial, both when it is explicit (with = default
) or implicit (if the special
member function is omitted).