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

网友投稿 188 2022-11-15

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

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(示例)

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(反面示例)

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

觉得本文有帮助?欢迎点赞并分享给更多的人。

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:C++核心准则C.60: 拷贝赋值运算符应该是以const&为参数,返回非常量引用类型的非虚函数
下一篇:苹果Lightning接口还能坚持多久
相关文章

 发表评论

暂时没有评论,来抢沙发吧~