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:(考虑以下代码:)
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);
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指针在函数内部进行了防空判断,报警。