Main Content

AUTOSAR C++14 Rule A13-5-1

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

Since R2020a

Description

Rule Definition

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

Rationale

Typically, you overload the subscript operator operator[] to provide read and write access to individual elements of an array or similar structure contained in a class. If you implement a non-const overload of operator[], you must also implement a const version of this overload. Otherwise, you cannot use operator[] to read elements of a const object.

This rule allows the implementation of a const overload of operator[] for read-only access without the corresponding non-const overload.

Polyspace Implementation

Polyspace® flags the definition of the non-const member function if no corresponding const version of the member function is implemented.

Troubleshooting

If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

#include <memory>
#include <iostream>

class MyList
{
private:
    static constexpr std::int32_t maxSize = 10;
    std::int32_t container[maxSize];

public:
    std::int32_t& operator[](std::int32_t index) //compliant, non-const version
    {
        return container[index];
    }
    const std::int32_t& operator[](std::int32_t index) const //compliant, const version
    {
        return container[index];
    }
};

class MyList_nc
{
private:
    static constexpr std::int32_t maxSize = 10;
    std::int32_t container[maxSize];

public:
    std::int32_t& operator[](std::int32_t index) //non-compliant, non-const version only
    {
        return container[index];
    }

};

void func() noexcept
{
    MyList list;
    list[2] = 3; // Uses non-const version of operator[]
    std::cout << list[2] << std::endl;

    const MyList clist = {};
    std::cout << clist[2] << std::endl; // Uses const version of operator[]


}

In this example, the overloads of operator[] in class MyList are compliant because both the const and non-const versions of the overload are implemented. In class MyList_nc, the member function is not compliant because only the non-const version was implemented.

Check Information

Group: Overloading
Category: Required, Automated

Version History

Introduced in R2020a