前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则ES.76:避免使用goto语句​

C++核心准则ES.76:避免使用goto语句​

作者头像
面向对象思考
发布2020-06-04 12:23:23
5210
发布2020-06-04 12:23:23
举报

ES.76: Avoid goto

ES.76:避免使用goto语句

Reason(原因)

Readability, avoidance of errors. There are better control structures for humans; goto is for machine generated code.

可读性,避免错误。存在另外的更好的代码结构可用。

Exception(例外)

Breaking out of a nested loop. In that case, always jump forwards.

从嵌套循环中跳出。这种情况下,总是向前(代码执行角度的向前,译者注)跳。

代码语言:javascript
复制
for (int i = 0; i < imax; ++i)
    for (int j = 0; j < jmax; ++j) {
        if (a[i][j] > elem_max) goto finished;
        // ...
    }
finished:
// ...
Example, bad(反面示例)

There is a fair amount of use of the C goto-exit idiom:

存在相当数量的使用goto-exit惯用法的C代码。

代码语言:javascript
复制
void f()
{
    // ...
        goto exit;
    // ...
        goto exit;
    // ...
exit:
    // ... common cleanup code ...
}

This is an ad-hoc simulation of destructors. Declare your resources with handles with destructors that clean up. If for some reason you cannot handle all cleanup with destructors for the variables used, consider gsl::finally() as a cleaner and more reliable alternative to goto exit。

这是析构函数特别合适的使用场景。定义资源管理类,在它的析构函数中执行清除动作。如果由于某种原因,析构函数不能在所有情况下中实现完全地清除,考虑使用gsl::finally作为清除器和goto的更可靠代替手段。

Enforcement(实施建议)

  • Flag goto. Better still flag all gotos that do not jump from a nested loop to the statement immediately after a nest of loops.
  • 标记goto语句。最好标识所有的goto语句。只有一种例外情况:从嵌套循环内跳转到紧接在循环之后的代码。

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es76-avoid-goto

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Reason(原因)
    • Example, bad(反面示例)
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档