AutosarC++17_03-A13.5.1

If “operator[]” is to be overloaded with a non-const version, const version shall also be implemented

Required inputs: IR

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 271715 2017-03-23 10:13:51Z piotr.tanski $
#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 [8]: 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