当重载等于运算符==,应该检查引用相等第一吗? [英] When overloading the equality operator==, should one check for reference equality first?

查看:140
本文介绍了当重载等于运算符==,应该检查引用相等第一吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当重载operator ==()时,我目前执行

  bool operator ==(const X& lhs,const X& ; rhs)
{
return& lhs ==& rhs || / *成员比较... * /;
}

这意味着我首先检查对象的引用是否相等,成员。这是正确的方式吗?有什么事情要记住吗?

解决方案

自我比较通常是罕见的,除非你是一个不可变的内部pImpl通常只能通过 std :: hash后的无序_ 容器中的 == / code>碰撞您的常规包装器或类似情况。



针对罕见情况进行优化通常是一个坏主意。这增加了代码的复杂性,并增加了测试开销。



如果比较昂贵或无限昂贵,可能存在异常,因此失败的指针比较的成本开始是微不足道的。另一个例外是自我比较异常昂贵,几乎自我(几乎同样昂贵)是非常罕见的,而自我比较有时会发生。



是的,保持你的代码简单,担心大规模爆发,不要不必要的pessimize,并优化后实际上注意到性能问题(即使它只是哇,那是慢,或蒙特卡罗剖析)。


When overloading operator==(), I currently do

bool operator==(const X& lhs, const X& rhs)
{
    return &lhs == &rhs || /* member comparisons ... */;
}

meaning I check first for reference equality of the objects and then for equality for all the members. Is this the "proper" way to do it? Are there any gotchas or things to remember? Is this implementation the most efficient way to do it?

解决方案

Self comparison is usually rare, unless you are an immutable internal pImpl that is usually only compared via == in an unordered_ container after a std::hash collision of your regular wrapper, or something similar.

Optimizing for rare cases is often a bad idea. It adds complexity to the code, and increases testing overhead.

An exception can exist if the comparison is expensive or boundlessly expensive, so that the cost of a failed pointer comparison at the start is trivial. Another exception is where self comparison is unusually expensive, and almost-self (which would be almost as expensive) is exceedingly rare, while self comparison sometimes happens.

The short answer is, keep your code simple, worry about large-order blowups, don't needlessly pessimize, and optimize after actually noticing a performance problem (even if it is just "wow, that was slow", or Monte Carlo profiling).

这篇关于当重载等于运算符==,应该检查引用相等第一吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆