SL.con.3:避免越界错误
Read or write beyond an allocated range of elements typically leads to bad errors, wrong results, crashes, and security violations.
超越分配得到的范围读写元素通常会导致恶劣的错误,不正确的结果,冲突,和安全违反。
Note(注意)
The standard-library functions that apply to ranges of elements all have (or could have) bounds-safe overloads that take span. Standard types such as vector can be modified to perform bounds-checks under the bounds profile (in a compatible way, such as by adding contracts), or used with at().
适用于某个范围内元素的标准库函数都有(或会有)一个适用span参数的边界安全的重载函数。类似vector的标准类型可以被改写以便执行符合边界规则群组要求的边界检查(以兼容的方式,例如通过增加契约)或者通过at()访问元素。
Ideally, the in-bounds guarantee should be statically enforced. For example:
理想情况下,应该静态实现边界内保证。例如:
Such loops are as fast as any unchecked/unsafe equivalent.
这样的循环和不检查边界、不保证安全的等价物同样快。
Often a simple pre-check can eliminate the need for checking of individual indices. For example
通常,简单的事前检查可以消除检查独立索引的需要。例如:
Such loops can be much faster than individually checked element accesses.
这样的循环可以比逐个检查元素访问的情况快很多。
Example, bad(反面示例)
void f()
{
array<int, 10> a, b;
memset(a.data(), 0, 10); // BAD, and contains a length error (length = 10 * sizeof(int))
memcmp(a.data(), b.data(), 10); // BAD, and contains a length error (length = 10 * sizeof(int))
}
Also, std::array<>::fill() or std::fill() or even an empty initializer are better candidate than memset().
同样,std::array<>::fill()或std::fill(),甚至空初始化器都可以作为memset的更好选择。
Example, good(范例)
void f()
{
array<int, 10> a, b, c{}; // c is initialized to zero
a.fill(0);
fill(b.begin(), b.end(), 0); // std::fill()
fill(b, 0); // std::fill() + Ranges TS
if ( a == b ) {
// ...
}
}
If code is using an unmodified standard library, then there are still workarounds that enable use of std::array and std::vector in a bounds-safe manner. Code can call the .at() member function on each class, which will result in an std::out_of_range exception being thrown. Alternatively, code can call the at() free function, which will result in fail-fast (or a customized action) on a bounds violation.
如果代码使用的是未经修改的标准库,仍然有变通的办法以边界安全的方式使用std::array和std::vector。代码可以调用每个类的.at()成员函数,它可以抛出std::out_of_range异常。或者,代码可以调用at()自由函数,它在边界违反时会触发快速失败(或者自定义的动作)。
void f(std::vector<int>& v, std::array<int, 12> a, int i)
{
v[0] = a[0]; // BAD
v.at(0) = a[0]; // OK (alternative 1)
at(v, 0) = a[0]; // OK (alternative 2)
v.at(0) = a[i]; // BAD
v.at(0) = a.at(i); // OK (alternative 1)
v.at(0) = at(a, i); // OK (alternative 2)
}
This rule is part of the bounds profile.
本规格是边界准则群组的一部分。
原文链接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#slcon3-avoid-bounds-errors