gsl::not_null 会影响性能吗?

Does gsl::not_null hurt performance?

C++ Core Guidelines recommends a gsl::not_null type. As stated in I.12: Declare a pointer that must not be null as not_null:

To help avoid dereferencing nullptr errors. To improve performance by avoiding redundant checks for 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.

(感兴趣的话,这是微软对gsl::not_null的实现:GitHub

指南文档说它通过“删除分支和空测试”来帮助提高性能。但是,它也增加了开销,因为如果我想访问底层指针,将调用方法 operator->()operator*()(这不包括 Microsoft 实现在这些方法中进行运行时检查的开销)。

鉴于无法保证方法内联,文档如何得出净性能增益为正的结论?

But, it also adds an overhead because methods operator->() and operator*()

除此之外,这些函数是内联定义的并且非常小,因此优化器(很可能)会内联扩展它们,这将完全消除潜在的开销。

how did the doc conclude the net performance gain is positive?

正如您所引用的,文档甚至没有承认相关的开销,所以这样的结论是微不足道的。

如果你的意思是文档的作者是如何得出这样的结论的,只有那些作者自己知道。它的范围可能从“他们测量了它的影响”到“他们做了一个假设”。