前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则ES.27:使用std::array或者stack_array在堆栈上构建数组

C++核心准则ES.27:使用std::array或者stack_array在堆栈上构建数组

作者头像
面向对象思考
发布2020-05-20 00:18:53
9680
发布2020-05-20 00:18:53
举报

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(反面示例)

代码语言:javascript
复制
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(示例)

代码语言:javascript
复制
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

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-04-30,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • ES.27: Use std::array or stack_array for arrays on the stack
    • Reason(原因)
      • Enforcement(实施建议)
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档