In Effective C++ Item 03, Use const whenever possible.
class Bigint
{
int _data[MAXLEN];
//...
public:
int& operator[](const int index) { return _data[index]; }
const int operator[](const int index) const { return _data[index]; }
//...
};
const int operator[] does make difference from int& operator[].
But what about:
int foo() { }
and
const int foo() { }
Seems like that they’re the same.
My question is, why we use const int operator[](const int index) const instead of int operator[](const int index) const ?
Top level cv-qualifiers on return types of non class type are ignored.
Which means that even if you write:
The return type is
int. If the return type is a reference, of course,the
constis no longer top level, and the distinction between:and
is significant. (Note too that in function declarations, like the above,
any top level cv-qualifiers are also ignored.)
The distinction is also relevant for return values of class type: if you
return
T const, then the caller cannot call non-const functions on thereturned value, e.g.: