50 lines
1.7 KiB
Plaintext
50 lines
1.7 KiB
Plaintext
== Why is this an issue?
|
|
|
|
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
|
|
|
|
[source,cpp]
|
|
----
|
|
template<typename T>
|
|
class MyVector {
|
|
public:
|
|
T& operator[] (unsigned index); // Noncompliant, missing const overload
|
|
};
|
|
----
|
|
|
|
|
|
=== Compliant solution
|
|
|
|
[source,cpp]
|
|
----
|
|
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.
|
|
|
|
|
|
== Resources
|
|
|
|
* https://isocpp.org/wiki/faq/const-correctness#const-overloading[Isocpp - What's the deal with "const-overloading"?]
|
|
|