Search code examples
c++operator-overloadingoperatorscomparison-operatorsmemcmp

Is it safe to implement operator== and operator< using std::memcmp?


After seeing this question, my first thought was that it'd be trivial to define generic equivalence and relational operators:

#include <cstring>

template<class T>
bool operator==(const T& a, const T& b) {

    return std::memcmp(&a, &b, sizeof(T)) == 0;

}

template<class T>
bool operator<(const T& a, const T& b) {

    return std::memcmp(&a, &b, sizeof(T)) < 0;

}

using namespace std::rel_ops would then become even more useful, since it would be made fully generic by the default implementations of operators == and <. Obviously this does not perform a memberwise comparison, but instead a bitwise one, as though the type contains only POD members. This is not entirely consistent with how C++ generates copy constructors, for instance, which do perform memberwise copying.

But I wonder whether the above implementation is indeed safe. The structures would naturally have the same packing, being of the same type, but are the contents of the padding guaranteed to be identical (e.g., filled with zeros)? Are there any reasons why or situations in which this wouldn't work?


Solution

  • Never do this unless you're 100% sure about the memory layout, compiler behavior, and you really don't care portability, and you really want to gain the efficiency

    SOURCE