Question

The following code will fail to compile under GCC because it does define operator== but does not define operator!=.

struct A {
    unsigned int m_i;
    bool operator == (const A& rhs) const { return m_i == rhs.m_i; }
};

bool f(const A& lhs, const A& rhs) { return lhs != rhs; }

Obviously it wants either

bool operator != (const A& rhs) const { return !(operator==(rhs)); }

or

bool operator != (const A& rhs) const { return m_i != rhs.m_i; }

Common wisdom seems to be that this is because !operator== adds an instruction and so is less efficient. This leads some programmers to dutifully write out their complex != expression in full, and over the years I've fixed a number of bugs resulting from mismatched operators.

Is this coercion to write both operators a case of premature/legacy optimization, or is there a good, solid, practical reason to do this code-doubling that I'm just somehow missing ?

Was it helpful?

Solution

I would say absent some overwhelming evidence to the contrary, it's purely premature optimization (not even legacy--I doubt there was ever a good reason for it, at least in anything approaching a C++ time-frame).

For what it's worth, §20.2.1 of the C++ standard defines a number of overloads in <utility> that will give you a != based on operator== and a >, >=, <= all based on operator<.

OTHER TIPS

Why not use this:

bool f(const A& lhs, const A& rhs) { return !(lhs == rhs); }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top