is null 优化_C++核心准则边译边学-I.12 用not_null定义不能为空的指针

ba413c5d58690f304776524bea8853f1.png

I.12: Declare a pointer that must not be null as not_null( 用not_null定义不能为空的指针)

Reason(原因)

To help avoid dereferencing nullptr errors. To improve performance by avoiding redundant checks for nullptr.

为了防止解引用nullptr错误。为了避免多余的空指针检查以提高性能。

译者注:解引用就是指针前面加*获取内容的操作。

Example(示例)

int length(const char* p); // it is not clear whether length(nullptr) is validlength(nullptr); // OK?int length(not_null p); // better: we can assume that p cannot be nullptrint length(const char* p); // we must assume that p can be nullptr

By stating the intent in source, implementers and tools can provide better diagnostics, such as finding some classes of errors through static analysis, and perform optimizations, such as removing branches and null tests.

通过在代码中说明目的,实现者和工具可以提供较好的诊断,例如通过静态分析发现某些类型的错误,执行性能优化,例如移除分支和空判断。

译者注:指的是上述代码中使用not_null的情况。

Note(注意)

not_null is defined in the guidelines support library.

not_null在准则支持库中被定义。

译者注:积极地使用准则库。

Note(注意)

The assumption that the pointer to char pointed to a C-style string (a zero-terminated string of characters) was still implicit, and a potential source of confusion and errors. Use czstring in preference to const char*.

指向字符的指针会指向一个C风格的字符串(以0结尾的字符串)这样一个假设还是没有说清楚,这会成为不确定性和错误的来源。在引用const char*时使用czstring。

// we can assume that p cannot be nullptr// we can assume that p points to a zero-terminated array of charactersint length(not_null p);

Note: length() is, of course, std::strlen() in disguise.

注意:length()当然是伪装的std::strlen。

Enforcement(实施建议)

  • (Simple) ((Foundation)) If a function checks a pointer parameter against nullptr before access, on all control-flow paths, then warn it should be declared not_null.(简单)((基础))如果一个函数在使用指针参数之前在所有控制流路径上进行空检查,那么发出应该参数被声明为not_null的警告信息。
  • (Complex) If a function with pointer return value ensures it is not nullptr on all return paths, then warn the return type should be declared not_null.(复杂)如果一个指针类型(返回值)函数在它的所有返回路径上都确认返回值不为空,那么发出返回值应该被定义为not_null的警告信息。

觉得本文有帮助?请分享给更多人。

更多更新文章,欢迎关注微信公众号【面向对象思考】

面向对象设计,面向对象编程,面向对象思考!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值