天天看点

C++核心准则​Pro.bounds:边界安全群组

Pro.bounds: Bounds safety profile

Pro.bounds:边界安全群组

This profile makes it easier to construct code that operates within the bounds of allocated blocks of memory. It does so by focusing on removing the primary sources of bounds violations: pointer arithmetic and array indexing. One of the core features of this profile is to restrict pointers to only refer to single objects, not arrays.

此规则群组使构建在分配的内存块范围内运行的代码更加容易。它通过专注于消除违背边界规则的主要来源来做到这一点:指针算术和数组索引。此规则群组的核心功能之一是将指针限制为仅引用单个对象,而不是数组。

We define bounds-safety to be the property that a program does not use an object to access memory outside of the range that was allocated for it. Bounds safety is intended to be complete only when combined with Type safety and Lifetime safety, which cover other unsafe operations that allow bounds violations.

我们将边界安全性定义为程序不通过对象访问为其分配的范围之外的内存的属性。仅当与类型安全性和生命周期安全性结合使用时,边界安全性才是完整的,后者包含允许违反边界的其他不安全操作。

Bounds safety profile summary:

边界安全群组概要:

  • Bounds.1: Don't use pointer arithmetic. Use span instead: Pass pointers to single objects (only) and Keep pointer arithmetic simple.

    Bound.1:不要使用指针算法。改用span:​​将指针传递给单个对象(仅)​​,并​​使指针的运算保持简单​​。

  • Bounds.2: Only index into arrays using constant expressions: Pass pointers to single objects (only) and Keep pointer arithmetic simple.

    Bounds.2:仅使用常量表达式对数组进行索引:​​(仅)将指针传递给单个对象​​,并​​使指针的运算保持简单​​。

  • Bounds.3: No array-to-pointer decay: Pass pointers to single objects (only) and Keep pointer arithmetic simple.

    Bounds.3:没有数组到指针的退化:​​将指针传递给单个对象(仅)​​,并​​使指针的运算保持简单​​。

  • Bounds.4: Don't use standard-library functions and types that are not bounds-checked: Use the standard library in a type-safe manner.

    Bounds.4:不要使用未经边界检查的标准库函数和类型:​​以类型安全的方式使用标准库​​。

Impact(影响)

Bounds safety implies that access to an object - notably arrays - does not access beyond the object's memory allocation. This eliminates a large class of insidious and hard-to-find errors, including the (in)famous "buffer overflow" errors. This closes security loopholes as well as a prominent source of memory corruption (when writing out of bounds). Even if an out-of-bounds access is "just a read", it can lead to invariant violations (when the accessed isn't of the assumed type) and "mysterious values."

边界安全性意味着对对象(尤其是数组)的访问不会超出对象的内存分配范围。这消除了许多隐患和难以发现的错误,包括(著名的)“缓冲区溢出”错误。这可以消除安全漏洞以及内存损坏的主要根源(超出限制时)。即使越界访问只是“读取”,它也可能导致违反不变量(当访问的类型不是假定的类型时)和“神秘的价值”。

原文链接

​​https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#probounds-bounds-safety-profile​​

新书介绍

​​《实战Python设计模式》​​是作者最近出版的新书,拜托多多关注!

C++核心准则​Pro.bounds:边界安全群组

本书利用Python 的标准GUI 工具包tkinter,通过可执行的示例对23 个设计模式逐个进行说明。这样一方面可以使读者了解真实的软件开发工作中每个设计模式的运用场景和想要解决的问题;另一方面通过对这些问题的解决过程进行说明,让读者明白在编写代码时如何判断使用设计模式的利弊,并合理运用设计模式。

对设计模式感兴趣而且希望随学随用的读者通过本书可以快速跨越从理解到运用的门槛;希望学习Python GUI 编程的读者可以将本书中的示例作为设计和开发的参考;使用Python 语言进行图像分析、数据处理工作的读者可以直接以本书中的示例为基础,迅速构建自己的系统架构。

觉得本文有帮助?请分享给更多人。

关注微信公众号【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!

继续阅读