ES.42: Keep use of pointers simple and straightforward
ES.42: 使用指针时要简单且直接
Reason(原因)
Complicated pointer manipulation is a major source of errors.
复杂的指针操作是错误的主要来源之一。
Note(注意)
Use gsl::span instead. Pointers should only refer to single objects. Pointer arithmetic is fragile and easy to get wrong, the source of many, many bad bugs and security violations.span is a bounds-checked, safe type for accessing arrays of data. Access into an array with known bounds using a constant as a subscript can be validated by the compiler.
使用gls::span。指针只应该用于参照单独的对象。指针运算脆弱且易错,会导致特别特别多的错误和安全违反。span类型提供了具有边界检查的、安全的访问数组数据的手段。使用常数下标访问一个已知边界的数组的操作可以在编译时检查。
Example, bad(反面示例)
Example, good(范例)
Note(注意)
Subscripting with a variable is difficult for both tools and humans to validate as safe.span is a run-time bounds-checked, safe type for accessing arrays of data.at() is another alternative that ensures single accesses are bounds-checked. If iterators are needed to access an array, use the iterators from a span constructed over the array.
使用变量下标的情况下确保安全性无论对工具还是人都很困难。span是访问数组数据的安全类型,可以提供执行时的范围检查。at()是确保单独访问时进行边界检查的另一种方式。如果迭代器需要访问数组,使用来自构建在数组之上的span的迭代器。
Example, bad(反面示例)
Example, good(范例)
Use a span:
使用span:
Use at():
使用at():
Example, bad(反面示例)
Example, good(范例)
Use a span:
使用span:
Use a span and range-for:
使用span和范围for:
Use at() for access:
使用at()访问:
Use a range-for:
使用范围for:
Note(注意)
Tooling can offer rewrites of array accesses that involve dynamic index expressions to use at() instead:
工具可以建议重写包含动态索引运算的数组访问代码,转而使用at()。
Example(示例)
Turning an array into a pointer (as the language does essentially always) removes opportunities for checking, so avoid it。
将数组转换为指针(像语言一直在做的那样)放弃了检查的机会,应该避免。
If you want to pass an array, say so:
如果想传递一个数组,这样做:
Enforcement(实施建议)
- Flag any arithmetic operation on an expression of pointer type that results in a value of pointer type.
- 标记对指针表达式进行数学运算然后得到指针类型的结果的情况。
- Flag any indexing expression on an expression or variable of array type (either static array or std::array) where the indexer is not a compile-time constant expression with a value between 0 and the upper bound of the array.
- 如果一个索引不是编译时可确定其值区间为0到数组上限的常量表达式,对数组类型变量或表达式的索引表达式的风险进行提示。
- Flag any expression that would rely on implicit conversion of an array type to a pointer type.
- 提示表达式依靠从数组到指针的隐式类型转换,提示。
This rule is part of the bounds-safety profile.
本规则是边界安全规则群组的一部分。
原文链接
觉得本文有帮助?欢迎点赞并分享给更多的人。
阅读更多更新文章,请关注微信公众号【面向对象思考】
















