简体   繁体   中英

Practical reason for defining operator!=

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 ?

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< .

为什么不使用这个:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM