Uploaded image for project: 'Rules Repository'
  1. Rules Repository
  2. RSPEC-6046

Subscript operator should be "const"-overloaded

    XMLWordPrintable

    Details

    • Default Severity:
      Major
    • Impact:
      Low
    • Likelihood:
      High
    • Default Quality Profiles:
      Sonar way, MISRA C++ 2008 recommended
    • Targeted languages:
      C++
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      2min
    • Analysis Scope:
      Main Sources, Test Sources

      Description

      Usually, it is the container data structures that define operator[] to mimic the traditional C-array interface. The subscript operator looks up an element in the container. It can return the element by value or by (optionally const) reference. You need a non-const subscript operator returning non-const reference to the element to be able to modify it. You need a const subscript operator to make a const-qualified instance of the container useful and enable the read-access with a consistent lookup interface.

      This rule raises an issue on a class that has a non-const operator[] overload that does not modify *this object but lacks a const overload.

      Noncompliant Code Example

      template<typename T>
      class MyVector {
      public:
        T& operator[] (unsigned index); // Noncompliant, missing const overload
      };
      

      Compliant Solution

      template<typename T>
      class MyArray {
      public:
        const T& operator[] (unsigned index) const; // Compliant
        // const-only operator and the compiler will tell you
        // when you try to use it in a non-const context and need an overload
      };
      template<typename T>
      class MyArray {
      public:
        T const& operator[] (unsigned index) const;
        T& operator[] (unsigned index); // Compliant, const-overloaded
      };
      

      Exceptions

      If operator[] might insert a new key, as it is done in std::map, or modifies the container in another externally-visible manner, there is no intuitive const overload for it.

      See

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              arseniy.zaostrovnykh Arseniy Zaostrovnykh
              Votes:
              0 Vote for this issue
              Watchers:
              1 Start watching this issue

                Dates

                Created:
                Updated: