C++核心准则ES.27:使用std::array或者stack_array在堆栈上构建数组
ES.27: Use std::array or stack_array for arrays on the stack
ES.27:使用std::array或者stack_array在堆栈上构建数组
Reason(原因)
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 a1;
stack_array a2(m);
// ...
}
Enforcement(实施建议)
Flag arrays with non-constant bounds (C-style VLAs)
标记变长数组(C风格不定长数组)
Flag arrays with non-local constant bounds
标记非局部常量定义长度的数组。
原文链接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es27-use-stdarray-or-stack_array-for-arrays-on-the-stack
觉得本文有帮助?请分享给更多人。
关注微信公众号【面向对象思考】轻松学习每一天!
面向对象开发,面向对象思考!