前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则​NR.6:不要将所有清理操作放在函数最后并使用goto语句跳转

C++核心准则​NR.6:不要将所有清理操作放在函数最后并使用goto语句跳转

作者头像
面向对象思考
发布2020-11-10 11:18:46
4750
发布2020-11-10 11:18:46
举报
文章被收录于专栏:C++核心准则原文翻译

NR.6: Don't place all cleanup actions at the end of a function and goto exit

NR.6:不要将所有清理操作放在函数最后并使用goto语句跳转

Reason(原因)

goto is error-prone. This technique is a pre-exception technique for RAII-like resource and error handling.

goto容易出错。该技术是用于类RAII的资源和错误处理的例外技术。

Example, bad(反面示例)

代码语言:javascript
复制
void do_something(int n)
{
    if (n < 100) goto exit;
    // ...
    int* p = (int*) malloc(n);
    // ...
    if (some_error) goto_exit;
    // ...
exit:
    free(p);
}

and spot the bug.

并找出错误。

Alternative(其他选项)

  • Use exceptions and RAII 使用例外和RAII
  • for non-RAII resources, use finally. 对于非RAII资源,使用finally处理

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#nr6-dont-place-all-cleanup-actions-at-the-end-of-a-function-and-goto-exit

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • NR.6: Don't place all cleanup actions at the end of a function and goto exit
  • Reason(原因)
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档