C++中为什么使用not_null<T>表明空是无效值

这篇文章主要讲解了“C++中为什么使用not_null表明空是无效值”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“C++中为什么使用not_null表明空是无效值”吧!

我们注重客户提出的每个要求,我们充分考虑每一个细节,我们积极的做好网站设计制作、成都网站设计服务,我们努力开拓更好的视野,通过不懈的努力,创新互联公司赢得了业内的良好声誉,这一切,也不断的激励着我们更好的服务客户。 主要业务:网站建设,网站制作,网站设计,小程序开发,网站开发,技术开发实力,DIV+CSS,PHP及ASP,ASP.Net,SQL数据库的技术开发工程师。

Reason(原因)

清晰性。一个使用not_null参数的函数可以明确地表明:如果有必要,调用者有责任进行空指针检查。类似的,返回not_null的函数向调用者清晰的表明了不需要进行nullptr的检查。

Example(示例)

not_null makes it obvious to a reader (human or machine) that a test for nullptr is not necessary before dereference. Additionally, when debugging, owner and not_null can be instrumented to check for correctness.

not_null向读者(人或机器)表明不需要在解引用之前进行nullptr检查。另外,在调试的时候,onwer和not_null可用于正确性检查。

Consider:(考虑以下代码:)

int length(Record* p);

When I call length(p) should I check if p is nullptr first? Should the implementation of length() check if p is nullptr?

在调用length(p)的时候需要首先检查p是否是nullptr吗?实现length()的时候应该检查p是否为nullptr吗?

// it is the caller's job to make sure p != nullptrint length(not_null p);
// the implementor of length() must assume that p == nullptr is possibleint length(Record* p);  

not_null被假定不会是nullptr;T*可能是nullptr;两者在内存上都表现为T*(因此不会付出额外的代价)。

Note(注意)

not_null is not just for built-in pointers. It works for unique_ptr, shared_ptr, and other pointer-like types.

not_null不止适用于内置指针。它也适用于unique_ptr和shared_ptr以及其他类似指针的类型。

Enforcement(实施建议)

  • (Simple) Warn if a raw pointer is dereferenced without being tested against nullptr (or equivalent) within a function, suggest it is declared not_null instead.

    (简单)处于某个函数中的裸指针如果没有进行nullptr(或等价的)检查就解引用,则报警。建议定义为not_null。

  • (Simple) Error if a raw pointer is sometimes dereferenced after first being tested against nullptr (or equivalent) within the function and sometimes is not.

    (简单)如果一个裸指针在解引用之前,有时会进行防空检查有时又不检查,报错。

  • (Simple) Warn if a not_null pointer is tested against nullptr within a function.

    (简单)如果not_null指针在函数内部进行了防空判断,报警。

感谢各位的阅读,以上就是“C++中为什么使用not_null表明空是无效值”的内容了,经过本文的学习后,相信大家对C++中为什么使用not_null表明空是无效值这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是创新互联,小编将为大家推送更多相关知识点的文章,欢迎关注!


分享题目:C++中为什么使用not_null<T>表明空是无效值
链接分享:http://bzwzjz.com/article/pghdei.html

其他资讯

Copyright © 2007-2020 广东宝晨空调科技有限公司 All Rights Reserved 粤ICP备2022107769号
友情链接: 成都网站建设公司 成都网站设计 营销网站建设 成都网站建设 成都网站设计 攀枝花网站设计 外贸网站设计方案 专业网站建设 网站设计 网站制作 成都网站建设 成都网站建设 宜宾网站设计 高端定制网站设计 高端网站设计 成都网站建设推广 企业网站设计 重庆网站设计 成都网站建设流程 成都网站设计 网站设计公司 网站建设方案