evaluate函数使用无效_C++核心准则编译边学-F.23 使用not_null表明“空”是无效值...

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

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

Reason(原因)

Clarity. A function with a not_null 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 makes it clear that the caller of the function does not need to check for nullptr.

清晰性。一个使用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);

Note(注意)

A not_null 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被假定不会是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指针在函数内部进行了防空判断,报警。

觉得本文有帮助?请分享给更多人。

更多更新文章,欢迎关注微信公众号【面向对象思考】

面向对象设计,面向对象编程,面向对象思考!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值