Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a safe way to implement a generic operator== and operator<?

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?

like image 951
Jon Purdy Avatar asked Aug 31 '10 14:08

Jon Purdy


1 Answers

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

like image 112
DumbCoder Avatar answered Sep 21 '22 14:09

DumbCoder