memcmp
over objects CXX-W2057Potentially incorrect calls to memcmp()
can lead to incorrect comparisons of object representations, especially for non-standard-layout types and types without unique object representations. This can be caused by padding or floating-point types. It is recommended to avoid using object representations for comparisons and instead use special member functions and overloaded operators.
struct NonStandardLayout {
int a;
char b;
int c;
};
NonStandardLayout obj1{1, 'a', 2};
NonStandardLayout obj2{1, 'a', 3};
int result = memcmp(&obj1, &obj2, sizeof(NonStandardLayout));
// The result may not accurately reflect the differences in the value representations
struct NonStandardLayout {
int a;
char b;
int c;
bool operator==(const NonStandardLayout& other) const {
return a == other.a && b == other.b && c == other.c;
}
};
NonStandardLayout obj1{1, 'a', 2};
NonStandardLayout obj2{1, 'a', 3};
bool result = (obj1 == obj2);
// Use a custom operator== function to compare the value representations instead