Why is this an issue?
The function memcmp
can only be used for objects of trivially copyable types. This includes scalar types, arrays, and trivially
copyable classes.
A class type is trivially copyable if:
- One or more of the following methods is trivial and the rest are deleted: copy constructor, move constructor, copy assignment operator, and
move assignment operator,
- It has a trivial, non-deleted destructor.
Additionally, if the type contains padding, some of its bits might be non-representative, and a strict comparison of raw memory contents might lead
to the mistaken belief that two identical objects are actually different.
Noncompliant code example
class Shape { // Trivially copyable, but will contain padding after the bool on most architectures
public:
bool visible;
int x;
int y;
};
bool isSame(Shape *s1, Shape *s2)
{
return memcmp(s1, s2, sizeof Shape) == 0; // Noncompliant
}
Compliant solution
class Shape {
public:
bool visible;
int x;
int y;
};
bool operator==(Shape const &s1, Shape const &s2) {
return s1.visible == s2.visible && s1.x == s2.x && s1.y == s2.y;
}
bool isSame(Shape *s1, Shape *s2)
{
return (*s1) == (*s2);
}