The problem with memcpy memcmp is that it compares the raw byte representation of an object, not the actual values of the object.
As others have mentioned, it will fail when the struct is not shallow, i.e. if it contains pointers, or if it contains any other members that contain pointers.
It will also fail if any of the members has a user-defined comarison operator (==).
For example, if any of the members of a sturct are const char *
, String
, float
, etc., you cannot use memcmp. Meaningful comparison of two const char *
strings requires strcmp
, not just a comparison of the pointers. String
contains a pointer to the actual string on the heap, so it's not shallow and requires a user-defined comparison operator. Floating point values can be equal (or not equal), even if their raw bit patterns are different (or the same), e.g. NaN != NaN and +0 == -0.
However, there's a much more serious problem: compilers are free to add padding bytes between members of a struct, and these padding bytes have indeterminate values. Therefore, comparing two structures with padding invokes undefined behavior (or implementation defined behavior?), because you have no guarantee that the padding bytes will be the same, even if all members are the same.
From cppreference:
This function reads object representations, not the object values, and is typically meaningful for byte arrays only: structs may have padding bytes whose values are indeterminate, the values of any bytes beyond the last stored member in a union are indeterminate, and a type may have two or more representations for the same value (different encodings for +0 and -0 or for +0.0 and –0.0, indeterminate padding bits within the type).
In conclusion, only use memcmp
to compare raw byte representations, use operator==
if you want to compare the values of two objects.
Overloading operator==
and operator!=
can be done as follows:
struct Inputs {
int input_01;
int input_02;
int input_03;
int input_04;
bool operator==(const Inputs &other) const {
return this->input_01 == other.input_01
&& this->input_02 == other.input_02
&& this->input_03 == other.input_03
&& this->input_04 == other.input_04;
}
bool operator!=(const Inputs &other) const {
return !(*this == other);
}
};
Pieter