| title | C26446 | |
|---|---|---|
| ms.date | 03/22/2018 | |
| ms.topic | reference | |
| f1_keywords |
|
|
| helpviewer_keywords |
|
Prefer to use gsl::at() instead of unchecked subscript operator.
C++ Core Guidelines: Bounds.4: Don't use standard-library functions and types that are not bounds-checked.
The Bounds profile of the C++ Core Guidelines tries to eliminate unsafe manipulations of memory by avoiding the use of raw pointers and unchecked operations. One way to perform uniform range-checked access to buffers is to use the gsl::at() utility from the Guidelines Support Library. It is also a good practice to rely on standard implementations of at() available in STL containers.
This rule helps to find places where potentially unchecked access is performed via calls to operator[](). In most cases such calls can be easily replaced by gsl::at().
- Access to arrays with known size is flagged when non-constant index is used in a subscript operator. Constant indices are handled by C26483 STATIC_INDEX_OUT_OF_RANGE.
- The logic to warn on overloaded operator[] calls is more complex:
- If index is non-integral, the call is ignored. This also handles indexing in standard maps since parameters in such operators are passed by reference.
- If the operator is marked as non-throwing (by using noexcept, throw(), or __declspec(nothrow)), the call is flagged. It is assumed that if the subscript operator never throws exceptions it either doesn’t perform range checks or these checks are obscure.
- If the operator is not marked as non-throwing, it may be flagged if it comes from an STL container that also defines a conventional
at()member function (such functions are detected by simple name matching). - The rule doesn’t warn on calls to standard
at()functions. These functions are safe and replacing them withgsl::at()would not bring much value.
- Indexing into
std::basic_string_view<>is not safe, so a warning is issued. The standard string view can be replaced bygsl::basic_string_span<>, which is always bounds-checked. - The implementation doesn’t consider range checks that user code may have somewhere in loops or branches. Accuracy here is traded for performance. In general, explicit range checks can often be replaced with more reliable iterators or more concise enhanced for-loops.