C++核心準(zhǔn)則ES.27:使用std::array或者stack_array在堆棧上構(gòu)建數(shù)組

ES.27: Use?std::array?or?stack_array?for arrays on the stack
ES.27:使用std::array或者stack_array在堆棧上構(gòu)建數(shù)組
Reason(原因)
They are readable and don't implicitly convert to pointers. They are not confused with non-standard extensions of built-in arrays.
它們的可讀性好,而且不會隱式轉(zhuǎn)換為指針類型。它們不會和內(nèi)置數(shù)組的非標(biāo)準(zhǔn)擴(kuò)展相混淆。
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++語法。存在很多這樣的代碼。雖然它容易出錯誤,特別是邊界不是局部變量時。同時它也是很多錯誤的常見原因(緩沖區(qū)溢出,退化數(shù)組的指針等)。a2是C語法而不是C++語法。在C++中被認(rèn)為存在安全風(fēng)險。
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)
標(biāo)記變長數(shù)組(C風(fēng)格不定長數(shù)組)
Flag arrays with non-local constant bounds
標(biāo)記非局部常量定義長度的數(shù)組。
原文鏈接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es27-use-stdarray-or-stack_array-for-arrays-on-the-stack
覺得本文有幫助?請分享給更多人。
關(guān)注微信公眾號【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
