前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则C.86:保证==语义遵守操作数规则并不会抛出异常

C++核心准则C.86:保证==语义遵守操作数规则并不会抛出异常

作者头像
面向对象思考
发布2020-03-25 16:25:06
3390
发布2020-03-25 16:25:06
举报

C.86: Make == symmetric with respect to operand types and noexcept

C.86:保证==语义遵守操作数规则并不会抛出异常

Reason(原因)

Asymmetric treatment of operands is surprising and a source of errors where conversions are possible.== is a fundamental operations and programmers should be able to use it without fear of failure.

操作数的非对称处理会令人诧异而且成为错误的源头当可能发生类型转换时。==是一个基础的操作而且程序员应该可以使用它而不必担心失败。

Example(示例)

代码语言:javascript
复制
struct X {
    string name;
    int number;
};

bool operator==(const X& a, const X& b) noexcept {
    return a.name == b.name && a.number == b.number;
}

Example, bad(反面示例)

代码语言:javascript
复制
class B {
    string name;
    int number;
    bool operator==(const B& a) const {
        return name == a.name && number == a.number;
    }
    // ...
};

B's comparison accepts conversions for its second operand, but not its first.

B的比较运算符可以接受第二个操作数的类型转换,但无法接受第一个参数的类型转换。

Note(注意)

If a class has a failure state, like double's NaN, there is a temptation to make a comparison against the failure state throw. The alternative is to make two failure states compare equal and any valid state compare false against the failure state.

如果一个类有失败状态,就像双精度数的NaN,就会产生一种诱惑在和失败状态对象比较是抛出异常。另外一种选择是将两个失败状态的比较结果视为相等,有效状态和无效状态的比较结果视为不相等。(而不抛出异常,译者注)

Note(注意)

This rule applies to all the usual comparison operators: !=, <, <=, >, and >=.

这条规则同样被适用于通常的比较运算符:!=, <, <=, >, 和 >=.

Enforcement(实施建议)

  • Flag an operator==() for which the argument types differ; same for other comparison operators: !=, <, <=, >, and >=. 如果相等运算符的参数是其他类型,进行提示。其他的比较运算符也一样:!=, <, <=, >, and >=。
  • Flag member operator==()s; same for other comparison operators: !=, <, <=, >, and >=. 标记成员函数比较运算符,其他的比较运算符也一样:!=, <, <=, >, and >=。

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c86-make--symmetric-with-respect-to-operand-types-and-noexcept


觉得本文有帮助?请分享给更多人。

关注【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-01-21,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档