本篇内容主要讲解“C++怎么避免基于全局状态的错误处理”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“C++怎么避免基于全局状态的错误处理”吧!
E.28:避免基于全局状态的错误处理(例如errno)
Reason(原因)
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的返回值是什么是时候?
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
// ...
}
Note(注意)
C-style error handling is based on the global variable errno, so it is essentially impossible to avoid this style completely.
C风格错误处理基于全局变量errno,因此这种风格的处理方式在本质上无法避免。
到此,相信大家对“C++怎么避免基于全局状态的错误处理”有了更深的了解,不妨来实际操作一番吧!这里是天达云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!