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