资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

C++怎么用not_null定义不能为空的指针

本篇内容主要讲解“C++怎么用not_null定义不能为空的指针”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“C++怎么用not_null定义不能为空的指针”吧!

专注于为中小企业提供网站设计、网站建设服务,电脑端+手机端+微信端的三站合一,更高效的管理,为中小企业抚宁免费做网站提供优质的服务。我们立足成都,凝聚了一批互联网行业人才,有力地推动了1000多家企业的稳健成长,帮助中小企业通过网站建设实现规模扩充和转变。

I.12: Declare a pointer that must not be null asnot_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 valid
length(nullptr);                      // OK?
int length(not_null p);  // better: we can assume that p cannot be nullptr
int 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的警告信息。

到此,相信大家对“C++怎么用not_null定义不能为空的指针”有了更深的了解,不妨来实际操作一番吧!这里是创新互联网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!


新闻名称:C++怎么用not_null定义不能为空的指针
网页地址:http://cdkjz.cn/article/gissoe.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220