前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则编译边学-F.23 使用not_null<T>表明“空”是无效值

C++核心准则编译边学-F.23 使用not_null<T>表明“空”是无效值

作者头像
面向对象思考
发布2020-03-25 15:24:39
5110
发布2020-03-25 15:24:39
举报
文章被收录于专栏:C++核心准则原文翻译

F.23: Use a not_null<T> to indicate that "null" is not a valid value(使用not_null<T>表明“空”是无效值)

Reason(原因)

Clarity. A function with a not_null<T> parameter makes it clear that the caller of the function is responsible for any nullptr checks that may be necessary. Similarly, a function with a return value of not_null<T> makes it clear that the caller of the function does not need to check for nullptr.

清晰性。一个使用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:(考虑以下代码:)

代码语言:javascript
复制
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吗?

代码语言:javascript
复制
// it is the caller's job to make sure p != nullptr
int length(not_null<Record*> p);

// the implementor of length() must assume that p == nullptr is possible
int length(Record* p);

Note(注意)

A not_null<T*> is assumed not to be the nullptr; a T* may be the nullptr; both can be represented in memory as a T* (so no run-time overhead is implied).

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指针在函数内部进行了防空判断,报警。
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2019-11-18,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • F.23: Use a not_null<T> to indicate that "null" is not a valid value(使用not_null<T>表明“空”是无效值)
    • Reason(原因)
      • Example(示例)
        • Note(注意)
          • Note(注意)
            • Enforcement(实施建议)
            领券
            问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档