温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2021-11-24 11:16:20 来源:亿速云 阅读:530 作者:iii 栏目:大数据

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

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 valid
length(nullptr);                      // OK?
int length(not_null<const char*> 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<zstring> 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定义不能为空的指针”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++
AI