【问题标题】:Practical reason for defining operator!=定义运算符的实际原因!=
【发布时间】:2014-01-21 04:29:53
【问题描述】:

以下代码将无法在 GCC 下编译,因为它确实定义了operator==,但没有定义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; }

显然它想要任何一个

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

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

普遍的看法似乎是这是因为!operator== 添加了一条指令,因此效率较低。这导致一些程序员尽职尽责地完整地写出他们复杂的!= 表达式,并且多年来我已经修复了许多由于运算符不匹配而导致的错误。

这种强制编写两个运算符是过早/遗留优化的情况,还是有一个很好的、可靠的、实际的理由来做这种我只是不知何故缺少的代码加倍?

【问题讨论】:

    标签: c++ operators comparison-operators


    【解决方案1】:

    我会说没有一些相反的压倒性证据,这纯粹是过早的优化(甚至不是遗留问题——我怀疑它是否有充分的理由,至少在任何接近 C++ 时间框架的情况下)。

    对于它的价值,C++ 标准的 §20.2.1 在<utility> 中定义了许多重载,这将为您提供基于operator==!=>>=、@987654326 @全部基于operator<

    【讨论】:

      【解决方案2】:

      为什么不用这个:

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

      【讨论】:

      • 请阅读问题:特别是我不是在问如何解决它,我已经举了这个例子,你只是省略了operator==operator
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-06
      • 2020-09-30
      • 1970-01-01
      • 1970-01-01
      • 2013-04-14
      • 2023-03-29
      • 2012-03-05
      相关资源
      最近更新 更多