C++核心準則R.2: 接口中只在表示單獨對象時使用原始指針​

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(反面示例)

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

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(示例)

<code>void g(int* p, int fmt)   // print *p using format #fmt
{

// ... uses *p and p[0] only ...
}/<code>

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


覺得本文有幫助?請分享給更多人。

關注【面向對象思考】輕鬆學習每一天!

面向對象開發,面向對象思考!


分享到:


相關文章: