Details
-
Type:
Code Smell Detection
-
Status: Active
-
Resolution: Unresolved
-
Labels:
-
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
- is implemented by
-
CPP-2718 Rule S6046: Subscript operator should be "const"-overloaded
-
- Open
-