C++核心準(zhǔn)則R.2: 只在接口中表示單獨(dú)對象使用原始指針?

R.2: In interfaces, use raw pointers to denote individual objects (only)
R.2: 只在接口中表示單獨(dú)對象使用原始指針
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.
數(shù)組最好用容器類型(例如,vector(具有所有權(quán)))或者span(不包含所有權(quán))表示。容器或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實(shí)際上指向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風(fēng)格字符串作為指向以0結(jié)尾的字符序列的指針傳遞。使用zstring而不是char*以表明你遵守這個習(xí)慣。
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.
很多目前指向單獨(dú)要素的指針可以使用引用。然而,當(dāng)nullptr也是有效值時引用就不是一個合理的選擇。
Enforcement(實(shí)施建議)
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或者迭代器并存在指針運(yùn)算(包括++),進(jìn)行提示。這條準(zhǔn)則如果運(yùn)用于舊代碼會產(chǎn)生大量的假陽性結(jié)果(結(jié)果有問題但實(shí)際上沒有問題,譯者注)。
Flag array names passed as simple pointers
提示用原始指針傳遞數(shù)組的情況。
原文鏈接:
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#r2-in-interfaces-use-raw-pointers-to-denote-individual-objects-only
覺得本文有幫助?請分享給更多人。
關(guān)注【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
