C++核心准则R.2: 只在接口中表示单独对象使用原始指针

R.2: In interfaces, use raw pointers to denote individual objects (only)

R.2: 只在接口中表示单独对象使用原始指针

 

Reason(原因)

Arrays are best represented by a container type (e.g., vector (owning)) or a span (non-owning). Such containers and views hold sufficient information to do range checking.

数组最好用容器类型(例如,vector(具有所有权))或者span(不包含所有权)表示。容器或span包含可以用于范围检查的信息。

 

Example, bad(反面示例)

void f(int* p, int n)   // n is the number of elements in p[]
{
    // ...
    p[2] = 7;   // bad: subscript raw pointer
    // ...
}

The compiler does not read comments, and without reading other code you do not know whether p really points to n elements. Use a span instead.

编译器不会读注释行,如果不看其他代码你无法知道p实际上指向n个元素。使用span吧。

 

Example(示例)

void g(int* p, int fmt)   // print *p using format #fmt
{
    // ... uses *p and p[0] only ...
}

 

Exception(例外)

C-style strings are passed as single pointers to a zero-terminated sequence of characters. Use zstring rather than char* to indicate that you rely on that convention.

C风格字符串作为指向以0结尾的字符序列的指针传递。使用zstring而不是char*以表明你遵守这个习惯。

 

Note(注意)

Many current uses of pointers to a single element could be references. However, where nullptr is a possible value, a reference may not be a reasonable alternative.

很多目前指向单独要素的指针可以使用引用。然而,当nullptr也是有效值时引用就不是一个合理的选择。

 

Enforcement(实施建议)

  • Flag pointer arithmetic (including ++) on a pointer that is not part of a container, view, or iterator. This rule would generate a huge number of false positives if applied to an older code base.

  • 如果一个指针不是来自容器,view或者迭代器并存在指针运算(包括++),进行提示。这条准则如果运用于旧代码会产生大量的假阳性结果(结果有问题但实际上没有问题,译者注)。

  • Flag array names passed as simple pointers

  • 提示用原始指针传递数组的情况。

 

原文链接:

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#r2-in-interfaces-use-raw-pointers-to-denote-individual-objects-only

 


 

觉得本文有帮助?欢迎点赞并分享给更多的人。

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

你可能感兴趣的:(C++)