前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则ES.79:使用default处理一般case

C++核心准则ES.79:使用default处理一般case

作者头像
面向对象思考
发布2020-06-09 15:07:07
2980
发布2020-06-09 15:07:07
举报

ES.79: Use default to handle common cases (only)

ES.79:使用default处理一般case

Reason(原因)

Code clarity. Improved opportunities for error detection.

代码清晰性。增加发现错误的机会。

Example(示例)

代码语言:javascript
复制
enum E { a, b, c , d };

void f1(E x)
{
    switch (x) {
    case a:
        do_something();
        break;
    case b:
        do_something_else();
        break;
    default:
        take_the_default_action();
        break;
    }
}

Here it is clear that there is a default action and that cases a and b are special.

可以清晰地看出存在一个默认case,而a和b是特殊case。

Example(示例)

But what if there is no default action and you mean to handle only specific cases? In that case, have an empty default or else it is impossible to know if you meant to handle all cases:

如果就是没有默认动作,你只想处理特殊case时应该怎么做呢?这种情况下,保留一个空的默认处理,否则不可能知道你是否意图处理所有case。

代码语言:javascript
复制
void f2(E x)
{
    switch (x) {
    case a:
        do_something();
        break;
    case b:
        do_something_else();
        break;
    default:
        // do nothing for the rest of the cases
        break;
    }
}

If you leave out the default, a maintainer and/or a compiler may reasonably assume that you intended to handle all cases:

如果漏掉了default,维护者或者编译器可能会合情合理的假设你意图处理所有case。

代码语言:javascript
复制
void f2(E x)
{
    switch (x) {
    case a:
        do_something();
        break;
    case b:
    case c:
        do_something_else();
        break;
    }
}

Did you forget case d or deliberately leave it out? Forgetting a case typically happens when a case is added to an enumeration and the person doing so fails to add it to every switch over the enumerators.

你是忘记了case d还是故意遗漏的?忘记一个case通常发生在增加枚举值之后却没有为所有switch语句增加针对该值的处理的时候。

Enforcement(实施建议)

Flag switch-statements over an enumeration that don't handle all enumerators and do not have a default. This may yield too many false positives in some code bases; if so, flag only switches that handle most but not all cases (that was the strategy of the very first C++ compiler).

标记针对枚举类型的、没有处理所有枚举值并且不包含default处理的switch语句。对于某些代码这种做法可能会产生太多的假阳性;如果发生这种情况,只标记处理了大部分case但不是全部case的情况(这正是很早期的C++编译器采用的策略)。

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es79-use-default-to-handle-common-cases-only

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • ES.79: Use default to handle common cases (only)
  • Reason(原因)
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档