前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则SL.con.3:避免越界错误

C++核心准则SL.con.3:避免越界错误

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

SL.con.3: Avoid bounds errors

SL.con.3:避免越界错误

Reason(原因)

Read or write beyond an allocated range of elements typically leads to bad errors, wrong results, crashes, and security violations.

超越分配得到的范围读写元素通常会导致恶劣的错误,不正确的结果,冲突,和安全违反。

Note(注意)

The standard-library functions that apply to ranges of elements all have (or could have) bounds-safe overloads that take span. Standard types such as vector can be modified to perform bounds-checks under the bounds profile (in a compatible way, such as by adding contracts), or used with at().

适用于某个范围内元素的标准库函数都有(或会有)一个适用span参数的边界安全的重载函数。类似vector的标准类型可以被改写以便执行符合边界规则群组要求的边界检查(以兼容的方式,例如通过增加契约)或者通过at()访问元素。

Ideally, the in-bounds guarantee should be statically enforced. For example:

理想情况下,应该静态实现边界内保证。例如:

  • a range-for cannot loop beyond the range of the container to which it is applied 范围for循环不会超越它操作的容器的范围。
  • a v.begin(),v.end() is easily determined to be bounds safe v.begin(),v.end()这种用法很容易判断是否边界安全。

Such loops are as fast as any unchecked/unsafe equivalent.

这样的循环和不检查边界、不保证安全的等价物同样快。

Often a simple pre-check can eliminate the need for checking of individual indices. For example

通常,简单的事前检查可以消除检查独立索引的需要。例如:

  • for v.begin(),v.begin()+i the i can easily be checked against v.size() 对于v.begin(),v.begin()+i,i可以简单的通过v.size()进行检查。

Such loops can be much faster than individually checked element accesses.

这样的循环可以比逐个检查元素访问的情况快很多。

Example, bad(反面示例)

代码语言:javascript
复制
void f()
{
    array<int, 10> a, b;
    memset(a.data(), 0, 10);         // BAD, and contains a length error (length = 10 * sizeof(int))
    memcmp(a.data(), b.data(), 10);  // BAD, and contains a length error (length = 10 * sizeof(int))
}

Also, std::array<>::fill() or std::fill() or even an empty initializer are better candidate than memset().

同样,std::array<>::fill()或std::fill(),甚至空初始化器都可以作为memset的更好选择。

Example, good(范例)

代码语言:javascript
复制
void f()
{
    array<int, 10> a, b, c{};       // c is initialized to zero
    a.fill(0);
    fill(b.begin(), b.end(), 0);    // std::fill()
    fill(b, 0);                     // std::fill() + Ranges TS

    if ( a == b ) {
      // ...
    }
}
Example(示例)

If code is using an unmodified standard library, then there are still workarounds that enable use of std::array and std::vector in a bounds-safe manner. Code can call the .at() member function on each class, which will result in an std::out_of_range exception being thrown. Alternatively, code can call the at() free function, which will result in fail-fast (or a customized action) on a bounds violation.

如果代码使用的是未经修改的标准库,仍然有变通的办法以边界安全的方式使用std::array和std::vector。代码可以调用每个类的.at()成员函数,它可以抛出std::out_of_range异常。或者,代码可以调用at()自由函数,它在边界违反时会触发快速失败(或者自定义的动作)。

代码语言:javascript
复制
void f(std::vector<int>& v, std::array<int, 12> a, int i)
{
    v[0] = a[0];        // BAD
    v.at(0) = a[0];     // OK (alternative 1)
    at(v, 0) = a[0];    // OK (alternative 2)

    v.at(0) = a[i];     // BAD
    v.at(0) = a.at(i);  // OK (alternative 1)
    v.at(0) = at(a, i); // OK (alternative 2)
}
Enforcement(实施建议)
  • Issue a diagnostic for any call to a standard-library function that is not bounds-checked. ??? insert link to a list of banned functions 发行一个检查,已确认所有对没有边界检查的标注库函数的调用。???插入禁止函数列表的链接。

This rule is part of the bounds profile.

本规格是边界准则群组的一部分。

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#slcon3-avoid-bounds-errors

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • SL.con.3: Avoid bounds errors
  • Reason(原因)
    • Example(示例)
      • Enforcement(实施建议)
      相关产品与服务
      容器服务
      腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档