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

发布时间:2021-11-24 11:50:57 作者:iii
来源:亿速云 阅读:289

这篇文章主要讲解了“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(实施建议)

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

推荐阅读:
  1. numpy 中怎么声明空数组
  2. 如何使用C++顺序表

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

c++

上一篇:C++怎么避免基于全局状态的错误处理

下一篇:怎么编写nodejs c++插件

相关阅读

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

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