Qt-Autosar-A13.5.1¶
If “operator[]” is to be overloaded with a non-const version, const version shall also be implemented
Required inputs: IR
| Level | required |
|---|---|
| Target | implementation |
| Enforcement | automated |
Rationale
A non-const overload of the subscript operator allows an object to be modified, by returning a reference to member data, but it does not allow reading from const objects.
The const version of “operator[]” needs to be implemented to ensure that the operator can be invoked on a const object.
Note that one can provide a const version of operator[] (to support read-only access to elements), but without a non-const version.
Example
// $Id: A13-5-1.cpp 289436 2017-10-04 10:45:23Z michal.szczepankiewicz $
#include <cstdint>
class Container1
{
public:
std::int32_t& operator[](
std::int32_t index) // Compliant - non-const version
{
return container[index];
}
std::int32_t operator[](
std::int32_t index) const // Compliant - const version
{
return container[index];
}
private:
static constexpr std::int32_t maxSize = 10;
std::int32_t container[maxSize];
};
void Fn() noexcept
{
Container1 c1;
std::int32_t e = c1[0]; // Non-const version called
c1[0] = 20; // Non-const version called
Container1 const c2{};
e = c2[0]; // Const version called
// c2[0] = 20; // Compilation error
}
class Container2 // Non-compliant - only non-const version of operator[]
// implemented
{
public:
std::int32_t& operator[](std::int32_t index) { return container[index]; }
private:
static constexpr std::int32_t maxSize = 10;
std::int32_t container[maxSize];
};
See Also
- HIC++ v4.0 [9]: 13.2.4 When overloading the subscript operator (operator[]) implement both const and non-const versions.
Possible Messages
Key |
Text |
Severity |
Disabled |
|---|---|---|---|
array_access_non_const |
No const version of operator[] implemented. |
None |
False |
Options
This rule shares the following common options: confidence, exclude_in_macros, exclude_messages_in_system_headers, excludes, extend_exclude_to_macro_invocations, includes, justification_checker, languages, post_processing, provider, report_at, severity
The following places define options that affect this rule: Stylechecks, Analysis-GlobalOptions
This rule has no individual options.