C++中为什么使用not_null<T>表明空是无效值
这篇文章主要讲解了"C++中为什么使用not_null
Reason(原因)
清晰性。一个使用not_null
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
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 != nullptr
int length(not_null
p);
// the implementor of length() must assume that p == nullptr is possible
int length(Record* p);
not_null
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 declarednot_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 againstnullptr
within a function.(简单)如果not_null指针在函数内部进行了防空判断,报警。
感谢各位的阅读,以上就是"C++中为什么使用not_null