E.28: Avoid error handling based on global state (e.g. errno)
E.28:避免基于全局状态的错误处理(例如errno)
Global state is hard to manage and it is easy to forget to check it. When did you last test the return value of printf()?
全局状态难于管理而且容易忘记检查。你上一次检查printf的返回值是什么是时候?
See also: Simulating RAII
参见:模仿RAII
Example, bad(反面示例)
int last_err;
void f(int n)
{
// ...
p = static_cast<X*>(malloc(n * sizeof(X)));
if (!p) last_err = -1; // error if memory is exhausted
// ...
}
C-style error handling is based on the global variable errno, so it is essentially impossible to avoid this style completely.
C风格错误处理基于全局变量errno,因此这种风格的处理方式在本质上无法避免。
Enforcement(实施建议)
Awkward.
很难。
原文链接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#e28-avoid-error-handling-based-on-global-state-eg-errno