首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >C++核心准则​SL.con.1:标准库array或vector好于C数组

C++核心准则​SL.con.1:标准库array或vector好于C数组

作者头像
面向对象思考
发布2020-10-30 11:29:04
发布2020-10-30 11:29:04
7140
举报

SL.con.1: Prefer using STL array or vector instead of a C array

SL.con.1:标准库array或vector好于C数组

Reason(原因)

C arrays are less safe, and have no advantages over array and vector. For a fixed-length array, use std::array, which does not degenerate to a pointer when passed to a function and does know its size. Also, like a built-in array, a stack-allocated std::array keeps its elements on the stack. For a variable-length array, use std::vector, which additionally can change its size and handles memory allocation.

C数组不够安全,和array或者vector相比没有任何优势。对于固定长度数组来讲,使用std::array,当被传递给某个函数时,它不会退化成指针无法获得长度。同时和内置的数组一样,堆栈上分配的std::array将元素保存在堆栈上。对于可变长度数组,使用std::vector,它可以进一步提供变更长度和惯例内存分配的功能。

Example(示例)

代码语言:javascript
复制
int v[SIZE];                        // BAD

std::array<int, SIZE> w;             // ok
Example(示例)
代码语言:javascript
复制
int* v = new int[initial_size];     // BAD, owning raw pointer
delete[] v;                         // BAD, manual delete

std::vector<int> w(initial_size);   // ok
Note(注意)

Use gsl::span for non-owning references into a container.

对于不包含所有权的容器参照,使用gsl::span

Note(注意)

Comparing the performance of a fixed-sized array allocated on the stack against a vector with its elements on the free store is bogus. You could just as well compare a std::array on the stack against the result of a malloc() accessed through a pointer. For most code, even the difference between stack allocation and free-store allocation doesn't matter, but the convenience and safety of vector does. People working with code for which that difference matters are quite capable of choosing between array and vector.

在分配于堆栈上固定长度数组和将元素分配于自由存储上的vector之间进行性能比较是没有意义的。比较指针访问堆栈上分配的std::array和malloc的结果倒是有些意义。对于大多数代码,堆栈分配和自由存储分配的(性能,译者注)区别没什么影响,然而vector却可以提供便利性和安全性。如果有些代码确实对这种区别敏感,人们完全可以在array和vector之间进行选择。

Enforcement(实施建议)

  • Flag declaration of a C array inside a function or class that also declares an STL container (to avoid excessive noisy warnings on legacy non-STL code). To fix: At least change the C array to a std::array. 标记同时在函数或类内部同时使用C数组和STL容器的情况(为了避免对既存的非STL代码过度报警)。修改方法:至少将C风格数组替换为std::array。

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#slcon1-prefer-using-stl-array-or-vector-instead-of-a-c-array

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • SL.con.1: Prefer using STL array or vector instead of a C array
    • Example(示例)
    • Note(注意)
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档