温馨提示×

温馨提示×

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

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

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

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

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

Reason(原因)

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

Example(示例)

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

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

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<Record*> p);
// the implementor of length() must assume that p == nullptr is possibleint length(Record* p);  

not_null<T*>被假定不会是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<T>表明空是无效值”的内容了,经过本文的学习后,相信大家对C++中为什么使用not_null<T>表明空是无效值这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

向AI问一下细节

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

c++
AI