最佳实践:如何检查C / C ++中的NULL返回值 [英] Best Practices: how to check for NULL return value in C/C++

查看:137
本文介绍了最佳实践:如何检查C / C ++中的NULL返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是C和C ++的样式问题。你喜欢

This is a style question for C and C++. Do you prefer

void f() {
  const char * x = g();
  if (x == NULL) {
    //process error
  }
  // continue function
}

或:

void f() {
  const char * x = g();
  if (! x) {
    //process error
  }
  // continue function
}

推荐答案

它主要取决于采用的约定

It mainly depends on the adopted convention within your group of work.

由于!= NULL 表单可能对开发人员更清楚,对于使用布尔形式检查 NULL 值的开发人员来说,也是如此。

As the != NULL form may be clearer to a developer who is used to it, the inverse is also true for developers who were used to check a NULL value using the boolean form.

As @Andy Prowl 提到它,通过使用 nullptr 类型在C ++ 11中更清晰的版本这个appeard: code> if(x == nullptr)。如果你正在编写C ++ 11应用程序,这个符号应该作为一个团队的每个成员使用。

As @Andy Prowl mentioned it, a much clearer version of this appeard in C++11 by the use of the nullptr type : if (x == nullptr). This notation should be used as a convention by every members of a team if you are writing C++11 application.

最后,存在不同的模式例如 空对象模式 ,可避免在您的代码中的任何地方进行此检查,以防此检查涉及您的应用程序的特定习惯。

Finally, there exists different patterns that are pretty much used such as the Null Object Pattern that avoids making this check everywhere in your code, in case this check involves a specific habit of your application.

这篇关于最佳实践:如何检查C / C ++中的NULL返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆