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<int, n> a1;
stack_array<int> 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
覺得本文有幫助?歡迎點贊並分享給更多的人。
閱讀更多更新文章,請關注微信公衆號【面向對象思考】