I.12: Declare a pointer that must not be null as ​​not_null(​​​ 用not_null定义不能为空的指针​​)​

 

Reason(原因)

To help avoid dereferencing ​​nullptr​​​ errors. To improve performance by avoiding redundant checks for ​​nullptr​​.

为了防止解引用nullptr错误。为了避免多余的空指针检查以提高性能。

译者注:解引用就是指针前面加*获取内容的操作。

Example(示例)


 

int length(const char* p);            // it is not clear whether length(nullptr) is valid
length(nullptr); // OK?
int length(not_null<const char*> p); // better: we can assume that p cannot be nullptr
int length(const char* p); // we must assume that p can be nullptr

By stating the intent in source, implementers and tools can provide better diagnostics, such as finding some classes of errors through static analysis, and perform optimizations, such as removing branches and null tests.

通过在代码中说明目的,实现者和工具可以提供较好的诊断,例如通过静态分析发现某些类型的错误,执行性能优化,例如移除分支和空判断。

译者注:指的是上述代码中使用not_null的情况。

Note(注意)

​not_null​​ is defined in the guidelines support library.

not_null在准则支持库中被定义。

译者注:积极地使用准则库。

Note(注意)

The assumption that the pointer to ​​char​​​ pointed to a C-style string (a zero-terminated string of characters) was still implicit, and a potential source of confusion and errors. Use ​​czstring​​​ in preference to ​​const char*​​.

指向字符的指针会指向一个C风格的字符串(以0结尾的字符串)这样一个假设还是没有说清楚,这会成为不确定性和错误的来源。在引用const char*时使用czstring。

 

// we can assume that p cannot be nullptr// we can assume that p points to a zero-terminated array of charactersint length(not_null<zstring> p);


 


Note: ​​length()​​​ is, of course, ​​std::strlen()​​ in disguise.

注意:length()当然是伪装的std::strlen。

Enforcement(实施建议)

  • (Simple) ((Foundation)) If a function checks a pointer parameter against​​nullptr​​​ before access, on all control-flow paths, then warn it should be declared​​not_null​​.

(简单)((基础))如果一个函数在使用指针参数之前在所有控制流路径上进行空检查,那么发出应该参数被声明为not_null的警告信息。

  • (Complex) If a function with pointer return value ensures it is not​​nullptr​​​ on all return paths, then warn the return type should be declared​​not_null​​.

(复杂)如果一个指针类型(返回值)函数在它的所有返回路径上都确认返回值不为空,那么发出返回值应该被定义为not_null的警告信息。