ES.27:使用std::array或者stack_array在堆栈上构建数组
They are readable and don't implicitly convert to pointers. They are not confused with non-standard extensions of built-in arrays.
它们的可读性好,而且不会隐式转换为指针类型。它们不会和内置数组的非标准扩展相混淆。
Example, bad(反面示例)
const int n = 7;
int m = 9;
void f()
{
int a1[n];
int a2[m]; // error: not ISO C++
// ...
}
Note(注意)
The definition of a1 is legal C++ and has always been. There is a lot of such code. It is error-prone, though, especially when the bound is non-local. Also, it is a "popular" source of errors (buffer overflow, pointers from array decay, etc.). The definition of a2 is C but not C++ and is considered a security risk.
a1的定义是一直都是合法的C++语法。存在很多这样的代码。虽然它容易出错误,特别是边界不是局部变量时。同时它也是很多错误的常见原因(缓冲区溢出,退化数组的指针等)。a2是C语法而不是C++语法。在C++中被认为存在安全风险。
Example(示例)
const int n = 7;
int m = 9;
void f()
{
array<int, n> a1;
stack_array<int> a2(m);
// ...
}
链接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es27-use-stdarray-or-stack_array-for-arrays-on-the-stack